﻿using CloudApiServer.Class;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using static log4net.Appender.RollingFileAppender;

namespace CloudApiServer.Services
{
    /// <summary>
    /// 药店结算服务 
    /// </summary>
    public class FsiDrugStoreService
    {
        
        private readonly DrugStoreCommonService _drugStoreCommonService;

        /// <summary>
        /// 构造函数
        /// </summary>
        public FsiDrugStoreService()
        {
            _drugStoreCommonService=new DrugStoreCommonService();
        }

        /// <summary>
        /// 2101/2101A药店预结算
        /// </summary>
        /// <param name="fsiRequest">预结算入参</param>
        /// <param name="ControllerName">来源控制器名称</param>
        /// <returns>预结算出参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<outputDrugstoreSettleAccountsPreA> DrugstoreSettleAccountsPre(FsiRequestHeader<InputDrugstoreSettleAccountsPreA> fsiRequest, string ControllerName)
        {
            List<DrugdetailDrugstoreSettleAccountsPreA> list = new List<DrugdetailDrugstoreSettleAccountsPreA>();
            list = fsiRequest.Input.drugdetail;
            string psn_no = fsiRequest.Input.druginfo.psn_no;
            string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
            if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(fsiRequest.fixmedins_code) || list.Count == 0)
            {
                throw new Exception("参数校验失败：传入的机构代码|人员编号|待结算的商品数组为空，请检查入参！" );
            }
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            DateTime dateTime = DateTime.Now;
            DataTable dtpsninfo = await _drugStoreCommonService.FetchPersonInfo(psn_no);
            if (dtpsninfo.Rows.Count != 1)
            {
                throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
            }
            //清算类别
            string clr_type =  _drugStoreCommonService.GetDrugStoreClrType(fsiRequest.Input.druginfo.med_type);
            // 生成就诊id 伪随机数
            string mdtrt_id = PublicMethod.GenerateRandomNumber(8);
            
            string expcontentJson = null;
            double clcYearAcctPay = 0;
            double Q0001 =0 ;
            double crtYearAcctPay= 0;
            double medIns_wallet_pay= 0;
            //浙江省序列化结算当年历年拓展字段
            if (ControllerName == "FsiApiZheJiangController" && fsiadmvs == "33")
            {
                clcYearAcctPay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.clcYearAcctPay, 2);
                Q0001 = 0;
                crtYearAcctPay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.crtYearAcctPay, 2);
                SetlinfoexpcontentZJ setlinfoexpcontent = new SetlinfoexpcontentZJ
                {
                    clcYearAcctPay = clcYearAcctPay,
                    Q0001 = Q0001,
                    crtYearAcctPay = crtYearAcctPay
                };
                expcontentJson = JsonConvert.SerializeObject(setlinfoexpcontent);
            }
            //陕西省序列化医保钱包拓展字段
            else if (ControllerName == "FsiApiZheJiangController" && fsiadmvs == "61")
            {
                var psninfo_exp_content = dtpsninfo.Rows[0]["exp_content"].ToString();
                if (!string.IsNullOrEmpty(psninfo_exp_content))
                {
                    JObject obj = JObject.Parse(psninfo_exp_content);
                    if (obj.TryGetValue("medIns_wallet_balance", out JToken balanceToken))
                    {
                        medIns_wallet_pay =
                            Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.medIns_wallet_pay, 2);
                        Setlinfoexpcontent setlinfoexpcontent = new Setlinfoexpcontent
                        {
                            medIns_wallet_balance = balanceToken.Value<double>()-medIns_wallet_pay,
                            medIns_wallet_pay =medIns_wallet_pay
                        };
                        expcontentJson = JsonConvert.SerializeObject(setlinfoexpcontent);
                    }
                }
            }
            
            using (var conn = new MySqlConnection(connectionString))
            {
                await conn.OpenAsync();
                using (MySqlTransaction transaction = conn.BeginTransaction())
                {
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {                        
                        cmd.Transaction = transaction; 
                        //处理订单汇总记录
                        try
                        {
                            cmd.CommandText = "INSERT INTO fsi_drugstore_order (order_state,stmt_type,order_source,order_canceltype,"+
                                              "opter_type,opter,opter_name,mdtrtarea_admvs,insuplc_admdvs,fixmedins_code,fixmedins_name,sign_no,"+
                                              "msgid,inf_time,infno,mdtrt_cert_type,mdtrt_cert_no,dise_codg,dise_name,insutype,acct_used_flag,psn_no,"+
                                              "med_type,begntime,exp_content,minpacunt_drug_trac_cnt,mcs_trac_cnt,setl_id,mdtrt_id,psn_name,psn_cert_type,certno,setl_time,medfee_sumamt,"+
                                              "fulamt_ownpay_amt,overlmt_selfpay,preselfpay_amt,inscp_scp_amt,act_pay_dedc,hifp_pay,pool_prop_selfpay,cvlserv_pay,"+
                                              "hifes_pay,hifob_pay,hifmi_pay,hifdm_pay,maf_pay,oth_pay,fund_pay_sumamt,psn_part_amt,acct_pay,psn_cash_pay,balc,acct_mulaid_pay,medins_setl_id,"+
                                              "clr_optins,clr_way,clr_type,clcYearAcctPay,crtYearAcctPay,Q0001,medIns_wallet_pay,create_time,update_time) VALUES (0,0,"+
                                              "@order_source,0,@opter_type,@opter,@opter_name,@mdtrtarea_admvs,@insuplc_admdvs,@fixmedins_code,"+
                                              "@fixmedins_name,@sign_no,@msgid,@inf_time,@infno,@mdtrt_cert_type,@mdtrt_cert_no,@dise_codg,@dise_name,@insutype,"+
                                              "@acct_used_flag,@psn_no,@med_type,@begntime,@exp_content,@minpacunt_drug_trac_cnt,@mcs_trac_cnt,@setl_id,@mdtrt_id,@psn_name,@psn_cert_type,@certno,@setl_time,"+
                                              "@medfee_sumamt,@fulamt_ownpay_amt,@overlmt_selfpay,@preselfpay_amt,@inscp_scp_amt,@act_pay_dedc,@hifp_pay,@pool_prop_selfpay,"+
                                              "@cvlserv_pay,@hifes_pay,@hifob_pay,@hifmi_pay,@hifdm_pay,@maf_pay,@oth_pay,@fund_pay_sumamt,@psn_part_amt,@acct_pay,@psn_cash_pay,@balc,@acct_mulaid_pay,"+
                                              "@medins_setl_id,@clr_optins,@clr_way,@clr_type,@clcYearAcctPay,@crtYearAcctPay,@Q0001,@medIns_wallet_pay,now(),now());"; 
                            cmd.Parameters.AddWithValue("@order_source", ControllerName);
                            cmd.Parameters.AddWithValue("@opter_type", fsiRequest.opter_type);
                            cmd.Parameters.AddWithValue("@opter", fsiRequest.opter);
                            cmd.Parameters.AddWithValue("@opter_name", fsiRequest.opter_name);
                            cmd.Parameters.AddWithValue("@mdtrtarea_admvs", fsiRequest.mdtrtarea_admvs);
                            cmd.Parameters.AddWithValue("@insuplc_admdvs", fsiRequest.insuplc_admdvs);
                            cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                            cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                            cmd.Parameters.AddWithValue("@sign_no", fsiRequest.sign_no);
                            cmd.Parameters.AddWithValue("@msgid", fsiRequest.msgid);
                            cmd.Parameters.AddWithValue("@inf_time", fsiRequest.inf_time);
                            cmd.Parameters.AddWithValue("@infno", fsiRequest.infno);
                            cmd.Parameters.AddWithValue("@mdtrt_cert_type", fsiRequest.Input.druginfo.mdtrt_cert_type);
                            cmd.Parameters.AddWithValue("@mdtrt_cert_no", fsiRequest.Input.druginfo.mdtrt_cert_no);
                            cmd.Parameters.AddWithValue("@dise_codg", fsiRequest.Input.druginfo.dise_codg);
                            cmd.Parameters.AddWithValue("@dise_name", fsiRequest.Input.druginfo.dise_name);
                            cmd.Parameters.AddWithValue("@insutype", fsiRequest.Input.druginfo.insutype);
                            cmd.Parameters.AddWithValue("@acct_used_flag", fsiRequest.Input.druginfo.acct_used_flag);
                            cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.druginfo.psn_no);
                            cmd.Parameters.AddWithValue("@med_type", fsiRequest.Input.druginfo.med_type);
                            cmd.Parameters.AddWithValue("@begntime", fsiRequest.Input.druginfo.begntime);
                            cmd.Parameters.AddWithValue("@exp_content",expcontentJson);
                            cmd.Parameters.AddWithValue("@minpacunt_drug_trac_cnt", fsiRequest.Input.druginfo.minpacunt_drug_trac_cnt);
                            cmd.Parameters.AddWithValue("@mcs_trac_cnt", fsiRequest.Input.druginfo.mcs_trac_cnt);
                            cmd.Parameters.AddWithValue("@setl_id", "");
                            cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                            cmd.Parameters.AddWithValue("@psn_name",dtpsninfo.Rows[0]["psn_name"].ToString());
                            cmd.Parameters.AddWithValue("@psn_cert_type",dtpsninfo.Rows[0]["psn_cert_type"].ToString());
                            cmd.Parameters.AddWithValue("@certno",dtpsninfo.Rows[0]["certno"].ToString());
                            cmd.Parameters.AddWithValue("@setl_time", dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                            cmd.Parameters.AddWithValue("@medfee_sumamt", fsiRequest.Input.druginfo.medfee_sumamt);
                            cmd.Parameters.AddWithValue("@fulamt_ownpay_amt", FsiDatainfo.fulamt_ownpay_amt);
                            cmd.Parameters.AddWithValue("@overlmt_selfpay", FsiDatainfo.overlmt_selfpay);
                            cmd.Parameters.AddWithValue("@preselfpay_amt", FsiDatainfo.preselfpay_amt);
                            cmd.Parameters.AddWithValue("@inscp_scp_amt", FsiDatainfo.inscp_scp_amt);
                            cmd.Parameters.AddWithValue("@act_pay_dedc", FsiDatainfo.act_pay_dedc);
                            cmd.Parameters.AddWithValue("@hifp_pay", fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt);
                            cmd.Parameters.AddWithValue("@pool_prop_selfpay",FsiDatainfo.fund_pay_sumamt);
                            cmd.Parameters.AddWithValue("@cvlserv_pay", FsiDatainfo.cvlserv_pay);
                            cmd.Parameters.AddWithValue("@hifes_pay", FsiDatainfo.hifes_pay);
                            cmd.Parameters.AddWithValue("@hifob_pay", FsiDatainfo.hifob_pay);
                            cmd.Parameters.AddWithValue("@hifmi_pay", FsiDatainfo.hifmi_pay);
                            cmd.Parameters.AddWithValue("@hifdm_pay", FsiDatainfo.hifdm_pay);
                            cmd.Parameters.AddWithValue("@maf_pay", FsiDatainfo.maf_pay);
                            cmd.Parameters.AddWithValue("@oth_pay", FsiDatainfo.oth_pay);
                            cmd.Parameters.AddWithValue("@fund_pay_sumamt", Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2));
                            cmd.Parameters.AddWithValue("@psn_part_amt", fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt);
                            cmd.Parameters.AddWithValue("@acct_pay",Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2));
                            cmd.Parameters.AddWithValue("@psn_cash_pay",Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.psn_cash_pay, 2));
                            cmd.Parameters.AddWithValue("@balc", Math.Round(Convert.ToDouble(dtpsninfo.Rows[0]["balc"]) - Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2), 2));
                            cmd.Parameters.AddWithValue("@acct_mulaid_pay", Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_mulaid_pay, 2));
                            cmd.Parameters.AddWithValue("@medins_setl_id", fsiRequest.msgid);
                            cmd.Parameters.AddWithValue("@clr_optins",$"{fsiRequest.mdtrtarea_admvs.Substring(0, 4)}99");
                            cmd.Parameters.AddWithValue("@clr_way", 1);
                            cmd.Parameters.AddWithValue("@clr_type", clr_type);
                            cmd.Parameters.AddWithValue("@clcYearAcctPay", clcYearAcctPay);
                            cmd.Parameters.AddWithValue("@crtYearAcctPay", crtYearAcctPay);
                            cmd.Parameters.AddWithValue("@Q0001", Q0001);
                            cmd.Parameters.AddWithValue("medIns_wallet_pay",medIns_wallet_pay);
                            await cmd.ExecuteNonQueryAsync();
                            cmd.Parameters.Clear();
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            throw new Exception($"预结算处理失败：插入订单汇总记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                        }
                        //处理订单明细记录
                        List<Detlcutinfo> dataList = new List<Detlcutinfo>();
                        foreach (var item in list)
                        {
                            //如果医疗类型不为41定点购药且处方号不为空，则校验处方号中是否存在该商品
                            //(fsiRequest.Input.druginfo.med_type != "41" || (ControllerName == "FsiApiZheJiangController" && fsiadmvs == "61")) && 
                            if (!string.IsNullOrEmpty(item.rxno))
                            {
                                bool isVerify = await _drugStoreCommonService.VerifyPrescriptionDrugs(item.rxno, fsiRequest.Input.druginfo.med_type, item.med_list_codg);
                                if (!isVerify)
                                {
                                    transaction.Rollback();
                                    throw new Exception($"处方药品明细校验失败：【{item.med_list_codg}】商品不存于处方【{item.rxno}】中。请注意只有在普通门诊处方下可以允许同一个药品替换同剂型同通用名不同厂家不同国家编码，其他医疗类别的处方强制要求处方上的国家编码与结算时入参的药品编码一致！【西药前18位编码一致，中成药前15位编码一致】，不符合业务要求！请检查!");
                                }
                            }
                            
                            try
                            {
                                 cmd.CommandText = "INSERT INTO fsi_drugstore_order_detail (msgid,setl_id,mdtrt_id,psn_no,feedetl_sn,rxno,rx_circ_flag,fee_ocur_time," +
                                              "med_list_codg,medins_list_codg,det_item_fee_sumamt,cnt,pric,sin_dos_dscr,used_frqu_dscr,prd_days,medc_way_dscr," +
                                              "bilg_dr_codg,bilg_dr_name,tcmdrug_used_way,exp_content,pric_uplmt_amt,selfpay_prop,fulamt_ownpay_amt,overlmt_amt," +
                                              "preselfpay_amt,inscp_scp_amt,chrgitm_lv,med_chrgitm_type,bas_medn_flag,hi_nego_drug_flag,chld_medc_flag,list_sp_item_flag," +
                                              "drt_reim_flag,memo,create_time,update_time) VALUES (@msgid,@setl_id,@mdtrt_id,@psn_no,@feedetl_sn,@rxno,@rx_circ_flag,@fee_ocur_time," +
                                              "@med_list_codg,@medins_list_codg,@det_item_fee_sumamt,@cnt,@pric,@sin_dos_dscr,@used_frqu_dscr,@prd_days,@medc_way_dscr,@bilg_dr_codg," +
                                              "@bilg_dr_name,@tcmdrug_used_way,@exp_content,@pric_uplmt_amt,@selfpay_prop,@fulamt_ownpay_amt,@overlmt_amt,@preselfpay_amt,@inscp_scp_amt," +
                                              "@chrgitm_lv,@med_chrgitm_type,@bas_medn_flag,@hi_nego_drug_flag,@chld_medc_flag,@list_sp_item_flag,@drt_reim_flag,@memo,now(),now())";
                                cmd.Parameters.AddWithValue("@msgid", fsiRequest.msgid);
                                cmd.Parameters.AddWithValue("@setl_id", null);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@psn_no", psn_no);
                                cmd.Parameters.AddWithValue("@feedetl_sn", item.feedetl_sn);
                                cmd.Parameters.AddWithValue("@rxno", item.rxno);
                                cmd.Parameters.AddWithValue("@rx_circ_flag", item.rx_circ_flag);
                                cmd.Parameters.AddWithValue("@fee_ocur_time", item.fee_ocur_time);
                                cmd.Parameters.AddWithValue("@med_list_codg", item.med_list_codg);
                                cmd.Parameters.AddWithValue("@medins_list_codg", item.medins_list_codg);
                                cmd.Parameters.AddWithValue("@det_item_fee_sumamt", item.det_item_fee_sumamt);
                                cmd.Parameters.AddWithValue("@cnt", item.cnt);
                                cmd.Parameters.AddWithValue("@pric", item.pric);
                                cmd.Parameters.AddWithValue("@sin_dos_dscr", item.sin_dos_dscr);
                                cmd.Parameters.AddWithValue("@used_frqu_dscr", item.used_frqu_dscr);
                                cmd.Parameters.AddWithValue("@prd_days", item.prd_days);
                                cmd.Parameters.AddWithValue("@medc_way_dscr", item.medc_way_dscr);
                                cmd.Parameters.AddWithValue("@bilg_dr_codg", item.bilg_dr_codg);
                                cmd.Parameters.AddWithValue("@bilg_dr_name", item.bilg_dr_name);
                                cmd.Parameters.AddWithValue("@tcmdrug_used_way", item.tcmdrug_used_way);
                                cmd.Parameters.AddWithValue("@exp_content", null);
                                cmd.Parameters.AddWithValue("@pric_uplmt_amt", item.det_item_fee_sumamt);
                                cmd.Parameters.AddWithValue("@selfpay_prop", 0);
                                cmd.Parameters.AddWithValue("@fulamt_ownpay_amt", 0);
                                cmd.Parameters.AddWithValue("@overlmt_amt", 0);
                                cmd.Parameters.AddWithValue("@preselfpay_amt", 0);
                                cmd.Parameters.AddWithValue("@inscp_scp_amt", item.det_item_fee_sumamt);
                                cmd.Parameters.AddWithValue("@chrgitm_lv", "03");
                                cmd.Parameters.AddWithValue("@med_chrgitm_type", "09");
                                cmd.Parameters.AddWithValue("@bas_medn_flag", "0");
                                cmd.Parameters.AddWithValue("@hi_nego_drug_flag", "0");
                                cmd.Parameters.AddWithValue("@chld_medc_flag", "0");
                                cmd.Parameters.AddWithValue("@list_sp_item_flag", "0");
                                cmd.Parameters.AddWithValue("@drt_reim_flag", "0");
                                cmd.Parameters.AddWithValue("@memo", null);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                                Detlcutinfo detlcutinfo = new Detlcutinfo
                                {
                                    bas_medn_flag = "0",
                                    med_chrgitm_type = "09",
                                    det_item_fee_sumamt = item.det_item_fee_sumamt,
                                    hi_nego_drug_flag = "0",
                                    fulamt_ownpay_amt = 0,
                                    cnt = item.cnt,
                                    pric = item.pric,
                                    feedetl_sn = item.feedetl_sn,
                                    inscp_scp_amt = item.det_item_fee_sumamt,
                                    drt_reim_flag = "0",
                                    overlmt_amt = 0,
                                    pric_uplmt_amt = item.det_item_fee_sumamt,
                                    selfpay_prop = 0,
                                    preselfpay_amt = 0,
                                    chrgitm_lv = "03"
                                };
                                dataList.Add(detlcutinfo);
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"预结算处理失败：插入订单明细【{item.med_list_codg}】记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                        }
                        //处理结算基金记录
                        List<Setldetail> setldetail = new List<Setldetail>();
                        try
                        {
                            cmd.CommandText =
                                "INSERT INTO fsi_drugstore_order_setldetail (msgid,setl_id,mdtrt_id,psn_no,fund_pay_type,inscp_scp_amt,crt_payb_lmt_amt," +
                                "fund_payamt,fund_pay_type_name,setl_proc_info,create_time,update_time) VALUES (@msgid,@setl_id,@mdtrt_id,@psn_no,@fund_pay_type," +
                                "@inscp_scp_amt,@crt_payb_lmt_amt,@fund_payamt,@fund_pay_type_name,@setl_proc_info,now(),now())";
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay != 0)
                            {
                                cmd.Parameters.AddWithValue("@msgid", fsiRequest.msgid);
                                cmd.Parameters.AddWithValue("@setl_id", null);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@psn_no", psn_no);
                                cmd.Parameters.AddWithValue("@fund_pay_type", "310200");
                                cmd.Parameters.AddWithValue("@inscp_scp_amt", 0);
                                cmd.Parameters.AddWithValue("@crt_payb_lmt_amt", 0);
                                cmd.Parameters.AddWithValue("@fund_payamt", Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2));
                                cmd.Parameters.AddWithValue("@fund_pay_type_name", "城镇职工基本医疗保险个人账户基金");
                                cmd.Parameters.AddWithValue("@setl_proc_info", null);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                                
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310200",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险个人账户基金"
                                };
                                setldetail.Add(detail);
                            }
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt != 0)
                            {
                                cmd.Parameters.AddWithValue("@msgid", fsiRequest.msgid);
                                cmd.Parameters.AddWithValue("@setl_id", null);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@psn_no", psn_no);
                                cmd.Parameters.AddWithValue("@fund_pay_type", "310100");
                                cmd.Parameters.AddWithValue("@inscp_scp_amt", 0);
                                cmd.Parameters.AddWithValue("@crt_payb_lmt_amt", 0);
                                cmd.Parameters.AddWithValue("@fund_payamt", Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2));
                                cmd.Parameters.AddWithValue("@fund_pay_type_name", "城镇职工基本医疗保险统筹基金");
                                cmd.Parameters.AddWithValue("@setl_proc_info", null);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310100",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险统筹基金"
                                };
                                setldetail.Add(detail);
                            }
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            throw new Exception($"预结算处理失败：插入结算基金记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                        }
                        transaction.Commit();
                        var output = new outputDrugstoreSettleAccountsPreA
                        {
                            detlcutinfo = dataList,
                            setlinfo = new Setlinfo
                            {
                                setl_time = dateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                cvlserv_pay = FsiDatainfo.cvlserv_pay,//公务员医疗补助资金
                                hifdm_pay = FsiDatainfo.hifdm_pay,//伤残人员医疗保障基金支出
                                cvlserv_flag = dtpsninfo.Rows[0]["cvlserv_flag"].ToString(),//公务员标志
                                med_type = fsiRequest.Input.druginfo.med_type,
                                exp_content = expcontentJson,
                                brdy = dtpsninfo.Rows[0]["brdy"].ToString(),
                                naty = dtpsninfo.Rows[0]["naty"].ToString(),//民族
                                psn_cash_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.psn_cash_pay, 2),//现金支付
                                certno =  dtpsninfo.Rows[0]["certno"].ToString(),//身份证号码
                                hifmi_pay = FsiDatainfo.hifmi_pay,//居民大病保险资金支出
                                psn_no = fsiRequest.Input.druginfo.psn_no,
                                act_pay_dedc = FsiDatainfo.act_pay_dedc,//实际支付起付线
                                mdtrt_cert_type = fsiRequest.Input.druginfo.mdtrt_cert_type,
                                balc = Math.Round(Convert.ToDouble(dtpsninfo.Rows[0]["balc"]) - Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2), 2),
                                medins_setl_id = fsiRequest.msgid,
                                psn_cert_type = dtpsninfo.Rows[0]["psn_cert_type"].ToString(),
                                acct_mulaid_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_mulaid_pay, 2),//个人账户共济支付金额
                                clr_way = "1",
                                hifob_pay = FsiDatainfo.hifob_pay,//职工大额医疗费用补助基金支出
                                oth_pay = FsiDatainfo.oth_pay,//其他支出
                                medfee_sumamt = fsiRequest.Input.druginfo.medfee_sumamt,
                                hifes_pay = FsiDatainfo.hifes_pay,//企业补充医疗保险基金支出
                                gend = dtpsninfo.Rows[0]["gend"].ToString(),
                                mdtrt_id = mdtrt_id,
                                acct_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),//个人账户支出
                                fund_pay_sumamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),//基金支付
                                fulamt_ownpay_amt = FsiDatainfo.fulamt_ownpay_amt,//全自费金额
                                hosp_part_amt = FsiDatainfo.hosp_part_amt,//医院负担金额
                                inscp_scp_amt = FsiDatainfo.inscp_scp_amt,//符合政策范围金额
                                insutype = fsiRequest.Input.druginfo.insutype,
                                maf_pay = FsiDatainfo.maf_pay, //医疗救助基金支出
                                psn_name = dtpsninfo.Rows[0]["psn_name"].ToString(),
                                psn_part_amt = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //个人负担总额
                                clr_optins = $"{fsiRequest.mdtrtarea_admvs.Substring(0, 4)}99",
                                pool_prop_selfpay = FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支付比例
                                psn_type =  dtpsninfo.Rows[0]["psn_type"].ToString(),
                                hifp_pay = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支出
                                overlmt_selfpay = FsiDatainfo.overlmt_selfpay, //超限价金额
                                preselfpay_amt = FsiDatainfo.preselfpay_amt, //先行自付金额
                                age = PublicMethod.CalculateAge(dtpsninfo.Rows[0]["brdy"].ToString(), dateTime),
                                clr_type = clr_type,
                            },
                            setldetail = setldetail
                        };
                        //如果开启了结算接口响应延迟配置 则延迟返回
                        if (FsiDatainfo.stateDrugStroeSettlePreDelay == true)
                        {
                            await Task.Delay(FsiDatainfo.drugStroeSettleDelayTime);
                        }
                        return output;
                    }
                }
            }
        }
        
        /// <summary>
        /// 2102/2102A药店结算
        /// </summary>
        /// <param name="fsiRequest">结算入参</param>
        /// <param name="ControllerName">来源控制器名称</param>
        /// <returns>结算出参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<outputDrugstoreSettleAccountsPreA> DrugstoreSettleAccounts(FsiRequestHeader<InputDrugstoreSettleAccountsPreA> fsiRequest, string ControllerName)
        {
            List<DrugdetailDrugstoreSettleAccountsPreA> list = new List<DrugdetailDrugstoreSettleAccountsPreA>();
            list = fsiRequest.Input.drugdetail;
            string psn_no = fsiRequest.Input.druginfo.psn_no;
            string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
            if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(fsiRequest.fixmedins_code) || list.Count == 0)
            {
                throw new Exception("参数校验失败：传入的机构代码|人员编号|待结算的商品数组为空，请检查入参！");
            }
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            Random rnd = new Random();
            DateTime dateTime = DateTime.Now;
            string query = "select * from fsi_PsnInfo where psn_no=@psn_no";
            var parameters = new List<MySqlParameter>
            {
                new MySqlParameter("@psn_no", psn_no),
            };
            DataTable dtpsninfo = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameters);
            if (dtpsninfo.Rows.Count != 1)
            {
                throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
            }
            //设置结算时间戳
            long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
            //清算类型 如果传入的是定点购药41 则清算类型为41药店，否则统一为11 门诊（不区分住院外配归到住院的部分）
            string clr_type = fsiRequest.Input.druginfo.med_type == "41" ? "41" : "11";
            //设置结算id与就诊id
            string mdtrt_id;
            string setl_id;
            //浙江省 如果是异地 则结算id需要短一点，不然会报错 模拟异地的结算id长度 取人员参保地长度前四位是否和入参参保地前四位是否一致
            if (ControllerName == "FsiApiZheJiangController" && fsiadmvs =="33" && fsiRequest.insuplc_admdvs.Substring(0, 4) != fsiRequest.mdtrtarea_admvs.Substring(0, 4))
            {
                mdtrt_id = $"{dtunix}";
                setl_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}";
            }
            else
            {
                mdtrt_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}";
                setl_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}";
            }

            string expcontentJson = null;
            double clcYearAcctPay = 0;
            double Q0001 =0 ;
            double crtYearAcctPay= 0;
            double medIns_wallet_pay= 0;
            //浙江省序列化结算当年历年拓展字段
            if (ControllerName == "FsiApiZheJiangController" && fsiadmvs == "33")
            {
                clcYearAcctPay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.clcYearAcctPay, 2);
                Q0001 = 0;
                crtYearAcctPay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.crtYearAcctPay, 2);
                SetlinfoexpcontentZJ setlinfoexpcontent = new SetlinfoexpcontentZJ
                {
                    clcYearAcctPay = clcYearAcctPay,
                    Q0001 = Q0001,
                    crtYearAcctPay = crtYearAcctPay
                };
                expcontentJson = JsonConvert.SerializeObject(setlinfoexpcontent);
            }
            //陕西省序列化医保钱包拓展字段
            else if (ControllerName == "FsiApiZheJiangController" && fsiadmvs == "61")
            {
                var psninfo_exp_content = dtpsninfo.Rows[0]["exp_content"].ToString();
                if (!string.IsNullOrEmpty(psninfo_exp_content))
                {
                    JObject obj = JObject.Parse(psninfo_exp_content);
                    if (obj.TryGetValue("medIns_wallet_balance", out JToken balanceToken))
                    {
                        medIns_wallet_pay =
                            Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.medIns_wallet_pay, 2);
                        Setlinfoexpcontent setlinfoexpcontent = new Setlinfoexpcontent
                        {
                            medIns_wallet_balance = balanceToken.Value<double>()-medIns_wallet_pay,
                            medIns_wallet_pay =medIns_wallet_pay
                        };
                        expcontentJson = JsonConvert.SerializeObject(setlinfoexpcontent);
                    }
                }
            }
            using (var conn = new MySqlConnection(connectionString))
            {
                await conn.OpenAsync();
                using (MySqlTransaction transaction = conn.BeginTransaction())
                {
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.Transaction = transaction;
                         //处理订单汇总记录
                        try
                        {
                            cmd.CommandText = "INSERT INTO fsi_drugstore_order (order_state,stmt_type,order_source,order_canceltype,"+
                                              "opter_type,opter,opter_name,mdtrtarea_admvs,insuplc_admdvs,fixmedins_code,fixmedins_name,sign_no,"+
                                              "msgid,inf_time,infno,mdtrt_cert_type,mdtrt_cert_no,dise_codg,dise_name,insutype,acct_used_flag,psn_no,"+
                                              "med_type,begntime,exp_content,minpacunt_drug_trac_cnt,mcs_trac_cnt,setl_id,mdtrt_id,psn_name,psn_cert_type,certno,setl_time,medfee_sumamt,"+
                                              "fulamt_ownpay_amt,overlmt_selfpay,preselfpay_amt,inscp_scp_amt,act_pay_dedc,hifp_pay,pool_prop_selfpay,cvlserv_pay,"+
                                              "hifes_pay,hifob_pay,hifmi_pay,hifdm_pay,maf_pay,oth_pay,fund_pay_sumamt,psn_part_amt,acct_pay,psn_cash_pay,balc,acct_mulaid_pay,medins_setl_id,"+
                                              "clr_optins,clr_way,clr_type,clcYearAcctPay,crtYearAcctPay,Q0001,medIns_wallet_pay,create_time,update_time) VALUES (1,0,"+
                                              "@order_source,0,@opter_type,@opter,@opter_name,@mdtrtarea_admvs,@insuplc_admdvs,@fixmedins_code,"+
                                              "@fixmedins_name,@sign_no,@msgid,@inf_time,@infno,@mdtrt_cert_type,@mdtrt_cert_no,@dise_codg,@dise_name,@insutype,"+
                                              "@acct_used_flag,@psn_no,@med_type,@begntime,@exp_content,@minpacunt_drug_trac_cnt,@mcs_trac_cnt,@setl_id,@mdtrt_id,@psn_name,@psn_cert_type,@certno,@setl_time,"+
                                              "@medfee_sumamt,@fulamt_ownpay_amt,@overlmt_selfpay,@preselfpay_amt,@inscp_scp_amt,@act_pay_dedc,@hifp_pay,@pool_prop_selfpay,"+
                                              "@cvlserv_pay,@hifes_pay,@hifob_pay,@hifmi_pay,@hifdm_pay,@maf_pay,@oth_pay,@fund_pay_sumamt,@psn_part_amt,@acct_pay,@psn_cash_pay,@balc,@acct_mulaid_pay,"+
                                              "@medins_setl_id,@clr_optins,@clr_way,@clr_type,@clcYearAcctPay,@crtYearAcctPay,@Q0001,@medIns_wallet_pay,now(),now());"; 
                            cmd.Parameters.AddWithValue("@order_source", ControllerName);
                            cmd.Parameters.AddWithValue("@opter_type", fsiRequest.opter_type);
                            cmd.Parameters.AddWithValue("@opter", fsiRequest.opter);
                            cmd.Parameters.AddWithValue("@opter_name", fsiRequest.opter_name);
                            cmd.Parameters.AddWithValue("@mdtrtarea_admvs", fsiRequest.mdtrtarea_admvs);
                            cmd.Parameters.AddWithValue("@insuplc_admdvs", fsiRequest.insuplc_admdvs);
                            cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                            cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                            cmd.Parameters.AddWithValue("@sign_no", fsiRequest.sign_no);
                            cmd.Parameters.AddWithValue("@msgid", fsiRequest.msgid);
                            cmd.Parameters.AddWithValue("@inf_time", fsiRequest.inf_time);
                            cmd.Parameters.AddWithValue("@infno", fsiRequest.infno);
                            cmd.Parameters.AddWithValue("@mdtrt_cert_type", fsiRequest.Input.druginfo.mdtrt_cert_type);
                            cmd.Parameters.AddWithValue("@mdtrt_cert_no", fsiRequest.Input.druginfo.mdtrt_cert_no);
                            cmd.Parameters.AddWithValue("@dise_codg", fsiRequest.Input.druginfo.dise_codg);
                            cmd.Parameters.AddWithValue("@dise_name", fsiRequest.Input.druginfo.dise_name);
                            cmd.Parameters.AddWithValue("@insutype", fsiRequest.Input.druginfo.insutype);
                            cmd.Parameters.AddWithValue("@acct_used_flag", fsiRequest.Input.druginfo.acct_used_flag);
                            cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.druginfo.psn_no);
                            cmd.Parameters.AddWithValue("@med_type", fsiRequest.Input.druginfo.med_type);
                            cmd.Parameters.AddWithValue("@begntime", fsiRequest.Input.druginfo.begntime);
                            cmd.Parameters.AddWithValue("@exp_content",expcontentJson);
                            cmd.Parameters.AddWithValue("@minpacunt_drug_trac_cnt", fsiRequest.Input.druginfo.minpacunt_drug_trac_cnt);
                            cmd.Parameters.AddWithValue("@mcs_trac_cnt", fsiRequest.Input.druginfo.mcs_trac_cnt);
                            cmd.Parameters.AddWithValue("@setl_id", setl_id);
                            cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                            cmd.Parameters.AddWithValue("@psn_name",dtpsninfo.Rows[0]["psn_name"].ToString());
                            cmd.Parameters.AddWithValue("@psn_cert_type",dtpsninfo.Rows[0]["psn_cert_type"].ToString());
                            cmd.Parameters.AddWithValue("@certno",dtpsninfo.Rows[0]["certno"].ToString());
                            cmd.Parameters.AddWithValue("@setl_time", dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                            cmd.Parameters.AddWithValue("@medfee_sumamt", fsiRequest.Input.druginfo.medfee_sumamt);
                            cmd.Parameters.AddWithValue("@fulamt_ownpay_amt", FsiDatainfo.fulamt_ownpay_amt);
                            cmd.Parameters.AddWithValue("@overlmt_selfpay", FsiDatainfo.overlmt_selfpay);
                            cmd.Parameters.AddWithValue("@preselfpay_amt", FsiDatainfo.preselfpay_amt);
                            cmd.Parameters.AddWithValue("@inscp_scp_amt", FsiDatainfo.inscp_scp_amt);
                            cmd.Parameters.AddWithValue("@act_pay_dedc", FsiDatainfo.act_pay_dedc);
                            cmd.Parameters.AddWithValue("@hifp_pay", fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt);
                            cmd.Parameters.AddWithValue("@pool_prop_selfpay",FsiDatainfo.fund_pay_sumamt);
                            cmd.Parameters.AddWithValue("@cvlserv_pay", FsiDatainfo.cvlserv_pay);
                            cmd.Parameters.AddWithValue("@hifes_pay", FsiDatainfo.hifes_pay);
                            cmd.Parameters.AddWithValue("@hifob_pay", FsiDatainfo.hifob_pay);
                            cmd.Parameters.AddWithValue("@hifmi_pay", FsiDatainfo.hifmi_pay);
                            cmd.Parameters.AddWithValue("@hifdm_pay", FsiDatainfo.hifdm_pay);
                            cmd.Parameters.AddWithValue("@maf_pay", FsiDatainfo.maf_pay);
                            cmd.Parameters.AddWithValue("@oth_pay", FsiDatainfo.oth_pay);
                            cmd.Parameters.AddWithValue("@fund_pay_sumamt", Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2));
                            cmd.Parameters.AddWithValue("@psn_part_amt", fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt);
                            cmd.Parameters.AddWithValue("@acct_pay",Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2));
                            cmd.Parameters.AddWithValue("@psn_cash_pay",Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.psn_cash_pay, 2));
                            cmd.Parameters.AddWithValue("@balc", Math.Round(Convert.ToDouble(dtpsninfo.Rows[0]["balc"]) - Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2), 2));
                            cmd.Parameters.AddWithValue("@acct_mulaid_pay", Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_mulaid_pay, 2));
                            cmd.Parameters.AddWithValue("@medins_setl_id", fsiRequest.msgid);
                            cmd.Parameters.AddWithValue("@clr_optins",$"{fsiRequest.mdtrtarea_admvs.Substring(0, 4)}99");
                            cmd.Parameters.AddWithValue("@clr_way", 1);
                            cmd.Parameters.AddWithValue("@clr_type", clr_type);
                            cmd.Parameters.AddWithValue("@clcYearAcctPay", clcYearAcctPay);
                            cmd.Parameters.AddWithValue("@crtYearAcctPay", crtYearAcctPay);
                            cmd.Parameters.AddWithValue("@Q0001", Q0001);
                            cmd.Parameters.AddWithValue("medIns_wallet_pay",medIns_wallet_pay);
                            await cmd.ExecuteNonQueryAsync();
                            cmd.Parameters.Clear();
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            throw new Exception($"结算处理失败：插入订单汇总记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                        }
                        //设置出参数商品列表
                        List<Detlcutinfo> dataList = new List<Detlcutinfo>();
                        //设置插入历史购药费用明细数组列表
                        List<FsiQuerydrugdosagInsert> FsiQuerydrugdosagInsertList = new List<FsiQuerydrugdosagInsert>();
                        foreach (var item in list)
                        {
                            if (!string.IsNullOrEmpty(item.rxno))
                            {
                                bool isVerify = await _drugStoreCommonService.VerifyPrescriptionDrugs(item.rxno, fsiRequest.Input.druginfo.med_type, item.med_list_codg);
                                if (!isVerify)
                                {
                                    transaction.Rollback();
                                    throw new Exception($"处方药品明细校验失败：【{item.med_list_codg}】商品不存于处方【{item.rxno}】中。请注意只有在普通门诊处方下可以允许同一个药品替换同剂型同通用名不同厂家不同国家编码，其他医疗类别的处方强制要求处方上的国家编码与结算时入参的药品编码一致！【西药前18位编码一致，中成药前15位编码一致】，不符合业务要求！请检查!");
                                }
                            }

                            try
                            {
                                 cmd.CommandText = "INSERT INTO fsi_drugstore_order_detail (msgid,setl_id,mdtrt_id,psn_no,feedetl_sn,rxno,rx_circ_flag,fee_ocur_time," +
                                              "med_list_codg,medins_list_codg,det_item_fee_sumamt,cnt,pric,sin_dos_dscr,used_frqu_dscr,prd_days,medc_way_dscr," +
                                              "bilg_dr_codg,bilg_dr_name,tcmdrug_used_way,exp_content,pric_uplmt_amt,selfpay_prop,fulamt_ownpay_amt,overlmt_amt," +
                                              "preselfpay_amt,inscp_scp_amt,chrgitm_lv,med_chrgitm_type,bas_medn_flag,hi_nego_drug_flag,chld_medc_flag,list_sp_item_flag," +
                                              "drt_reim_flag,memo,create_time,update_time) VALUES (@msgid,@setl_id,@mdtrt_id,@psn_no,@feedetl_sn,@rxno,@rx_circ_flag,@fee_ocur_time," +
                                              "@med_list_codg,@medins_list_codg,@det_item_fee_sumamt,@cnt,@pric,@sin_dos_dscr,@used_frqu_dscr,@prd_days,@medc_way_dscr,@bilg_dr_codg," +
                                              "@bilg_dr_name,@tcmdrug_used_way,@exp_content,@pric_uplmt_amt,@selfpay_prop,@fulamt_ownpay_amt,@overlmt_amt,@preselfpay_amt,@inscp_scp_amt," +
                                              "@chrgitm_lv,@med_chrgitm_type,@bas_medn_flag,@hi_nego_drug_flag,@chld_medc_flag,@list_sp_item_flag,@drt_reim_flag,@memo,now(),now())";
                                cmd.Parameters.AddWithValue("@msgid", fsiRequest.msgid);
                                cmd.Parameters.AddWithValue("@setl_id", setl_id);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@psn_no", psn_no);
                                cmd.Parameters.AddWithValue("@feedetl_sn", item.feedetl_sn);
                                cmd.Parameters.AddWithValue("@rxno", item.rxno);
                                cmd.Parameters.AddWithValue("@rx_circ_flag", item.rx_circ_flag);
                                cmd.Parameters.AddWithValue("@fee_ocur_time", item.fee_ocur_time);
                                cmd.Parameters.AddWithValue("@med_list_codg", item.med_list_codg);
                                cmd.Parameters.AddWithValue("@medins_list_codg", item.medins_list_codg);
                                cmd.Parameters.AddWithValue("@det_item_fee_sumamt", item.det_item_fee_sumamt);
                                cmd.Parameters.AddWithValue("@cnt", item.cnt);
                                cmd.Parameters.AddWithValue("@pric", item.pric);
                                cmd.Parameters.AddWithValue("@sin_dos_dscr", item.sin_dos_dscr);
                                cmd.Parameters.AddWithValue("@used_frqu_dscr", item.used_frqu_dscr);
                                cmd.Parameters.AddWithValue("@prd_days", item.prd_days);
                                cmd.Parameters.AddWithValue("@medc_way_dscr", item.medc_way_dscr);
                                cmd.Parameters.AddWithValue("@bilg_dr_codg", item.bilg_dr_codg);
                                cmd.Parameters.AddWithValue("@bilg_dr_name", item.bilg_dr_name);
                                cmd.Parameters.AddWithValue("@tcmdrug_used_way", item.tcmdrug_used_way);
                                cmd.Parameters.AddWithValue("@exp_content", null);
                                cmd.Parameters.AddWithValue("@pric_uplmt_amt", item.det_item_fee_sumamt);
                                cmd.Parameters.AddWithValue("@selfpay_prop", 0);
                                cmd.Parameters.AddWithValue("@fulamt_ownpay_amt", 0);
                                cmd.Parameters.AddWithValue("@overlmt_amt", 0);
                                cmd.Parameters.AddWithValue("@preselfpay_amt", 0);
                                cmd.Parameters.AddWithValue("@inscp_scp_amt", item.det_item_fee_sumamt);
                                cmd.Parameters.AddWithValue("@chrgitm_lv", "03");
                                cmd.Parameters.AddWithValue("@med_chrgitm_type", "09");
                                cmd.Parameters.AddWithValue("@bas_medn_flag", "0");
                                cmd.Parameters.AddWithValue("@hi_nego_drug_flag", "0");
                                cmd.Parameters.AddWithValue("@chld_medc_flag", "0");
                                cmd.Parameters.AddWithValue("@list_sp_item_flag", "0");
                                cmd.Parameters.AddWithValue("@drt_reim_flag", "0");
                                cmd.Parameters.AddWithValue("@memo", null);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                                Detlcutinfo detlcutinfo = new Detlcutinfo
                                {
                                    bas_medn_flag = "0",
                                    med_chrgitm_type = "09",
                                    det_item_fee_sumamt = item.det_item_fee_sumamt,
                                    hi_nego_drug_flag = "0",
                                    fulamt_ownpay_amt = 0,
                                    cnt = item.cnt,
                                    pric = item.pric,
                                    feedetl_sn = item.feedetl_sn,
                                    inscp_scp_amt = item.det_item_fee_sumamt,
                                    drt_reim_flag = "0",
                                    overlmt_amt = 0,
                                    pric_uplmt_amt = item.det_item_fee_sumamt,
                                    selfpay_prop = 0,
                                    preselfpay_amt = 0,
                                    chrgitm_lv = "03"
                                };
                                dataList.Add(detlcutinfo);
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"结算处理失败：插入订单明细【{item.med_list_codg}】记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }

                            try
                            {
                                //插入90天购药明细记录
                                FsiQuerydrugdosagInsert FsiQuerydrugdosagInsert = new FsiQuerydrugdosagInsert
                                {
                                    mdtrtId = setl_id,
                                    feeOcurTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                    hilistCode = item.med_list_codg,
                                    psnno = psn_no,
                                    fixmedins_code = fsiRequest.fixmedins_code,
                                    fixmedins_name = fsiRequest.fixmedins_name,
                                    usedFrquDscr = item.used_frqu_dscr,
                                    sinDosDscr = item.sin_dos_dscr,
                                    cnt = item.cnt,
                                    medinsListCodg = item.medins_list_codg,
                                    chrgitmLv = item.chrgitm_lv,
                                    pric = item.pric,
                                    detItemFeeSumamt = item.det_item_fee_sumamt,
                                    bilgDrCode = item.bilg_dr_codg,
                                    bilgDrName = item.bilg_dr_name,
                                    ds = dateTime.ToString("yyyyMMdd")
                                };
                                await _drugStoreCommonService.InsertQuerydrugdosag(FsiQuerydrugdosagInsert,
                                    transaction);
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"结算处理失败：插入90天购药明细【{item.med_list_codg}】记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                        }
                        //处理结算基金记录
                        List<Setldetail> setldetail = new List<Setldetail>();
                        try
                        {
                            cmd.CommandText =
                                "INSERT INTO fsi_drugstore_order_setldetail (msgid,setl_id,mdtrt_id,psn_no,fund_pay_type,inscp_scp_amt,crt_payb_lmt_amt," +
                                "fund_payamt,fund_pay_type_name,setl_proc_info,create_time,update_time) VALUES (@msgid,@setl_id,@mdtrt_id,@psn_no,@fund_pay_type," +
                                "@inscp_scp_amt,@crt_payb_lmt_amt,@fund_payamt,@fund_pay_type_name,@setl_proc_info,now(),now())";
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay != 0)
                            {
                                cmd.Parameters.AddWithValue("@msgid", fsiRequest.msgid);
                                cmd.Parameters.AddWithValue("@setl_id", setl_id);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@psn_no", psn_no);
                                cmd.Parameters.AddWithValue("@fund_pay_type", "310200");
                                cmd.Parameters.AddWithValue("@inscp_scp_amt", 0);
                                cmd.Parameters.AddWithValue("@crt_payb_lmt_amt", 0);
                                cmd.Parameters.AddWithValue("@fund_payamt", Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2));
                                cmd.Parameters.AddWithValue("@fund_pay_type_name", "城镇职工基本医疗保险个人账户基金");
                                cmd.Parameters.AddWithValue("@setl_proc_info", null);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                                
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310200",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险个人账户基金"
                                };
                                setldetail.Add(detail);
                            }
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt != 0)
                            {
                                cmd.Parameters.AddWithValue("@msgid", fsiRequest.msgid);
                                cmd.Parameters.AddWithValue("@setl_id", setl_id);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@psn_no", psn_no);
                                cmd.Parameters.AddWithValue("@fund_pay_type", "310100");
                                cmd.Parameters.AddWithValue("@inscp_scp_amt", 0);
                                cmd.Parameters.AddWithValue("@crt_payb_lmt_amt", 0);
                                cmd.Parameters.AddWithValue("@fund_payamt", Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2));
                                cmd.Parameters.AddWithValue("@fund_pay_type_name", "城镇职工基本医疗保险统筹基金");
                                cmd.Parameters.AddWithValue("@setl_proc_info", null);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310100",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险统筹基金"
                                };
                                setldetail.Add(detail);
                            }
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            throw new Exception($"结算处理失败：插入结算基金记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                        }


                        //插入年度费用累计
                        try
                        {
                            await _drugStoreCommonService.InsertQueryfixmedinspracpsnsum(
                                fsiRequest.Input.druginfo.psn_no, "S1100", dateTime.ToString("yyyy"),
                                decimal.Parse(fsiRequest.Input.druginfo.medfee_sumamt.ToString()),
                                dateTime.ToString("yyyyMM"), dtpsninfo.Rows[0]["insutype"].ToString(), transaction);
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            throw new Exception($"结算处理失败：插入费用累计记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                        }
                        
                        var output = new outputDrugstoreSettleAccountsPreA
                        {
                            detlcutinfo = dataList,
                            setlinfo = new Setlinfo
                            {
                                setl_time = dateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                cvlserv_pay = FsiDatainfo.cvlserv_pay,//公务员医疗补助资金
                                hifdm_pay = FsiDatainfo.hifdm_pay,//伤残人员医疗保障基金支出
                                cvlserv_flag = dtpsninfo.Rows[0]["cvlserv_flag"].ToString(),//公务员标志
                                med_type = fsiRequest.Input.druginfo.med_type,
                                exp_content = expcontentJson,
                                brdy = dtpsninfo.Rows[0]["brdy"].ToString(),
                                naty = dtpsninfo.Rows[0]["naty"].ToString(),//民族
                                psn_cash_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.psn_cash_pay, 2),//现金支付
                                certno = dtpsninfo.Rows[0]["certno"].ToString(),//身份证号码
                                hifmi_pay = FsiDatainfo.hifmi_pay,//居民大病保险资金支出
                                psn_no = fsiRequest.Input.druginfo.psn_no,
                                act_pay_dedc = FsiDatainfo.act_pay_dedc,//实际支付起付线
                                mdtrt_cert_type = fsiRequest.Input.druginfo.mdtrt_cert_type,

                                balc = Math.Round(Convert.ToDouble(dtpsninfo.Rows[0]["balc"]) - Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2), 2),
                                medins_setl_id = fsiRequest.msgid,
                                psn_cert_type =  dtpsninfo.Rows[0]["psn_cert_type"].ToString(),
                                acct_mulaid_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_mulaid_pay, 2),//个人账户共济支付金额
                                clr_way = "1",
                                hifob_pay = FsiDatainfo.hifob_pay,//职工大额医疗费用补助基金支出
                                oth_pay = FsiDatainfo.oth_pay,//其他支出
                                medfee_sumamt = fsiRequest.Input.druginfo.medfee_sumamt,
                                hifes_pay = FsiDatainfo.hifes_pay,//企业补充医疗保险基金支出
                                gend = dtpsninfo.Rows[0]["gend"].ToString(),
                                mdtrt_id = mdtrt_id,
                                acct_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),//个人账户支出
                                fund_pay_sumamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),//基金支付
                                fulamt_ownpay_amt = FsiDatainfo.fulamt_ownpay_amt,//全自费金额
                                hosp_part_amt = FsiDatainfo.hosp_part_amt,//医院负担金额
                                setl_id = setl_id,
                                inscp_scp_amt = FsiDatainfo.inscp_scp_amt,//符合政策范围金额
                                insutype = fsiRequest.Input.druginfo.insutype,
                                maf_pay = FsiDatainfo.maf_pay, //医疗救助基金支出
                                psn_name = dtpsninfo.Rows[0]["psn_name"].ToString(),
                                psn_part_amt = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //个人负担总额
                                clr_optins = $"{fsiRequest.mdtrtarea_admvs.Substring(0, 4)}99",
                                pool_prop_selfpay = FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支付比例
                                psn_type = dtpsninfo.Rows[0]["psn_type"].ToString(),
                                hifp_pay = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支出
                                overlmt_selfpay = FsiDatainfo.overlmt_selfpay, //超限价金额
                                preselfpay_amt = FsiDatainfo.preselfpay_amt, //先行自付金额
                                age = PublicMethod.CalculateAge(dtpsninfo.Rows[0]["brdy"].ToString(), dateTime),
                                clr_type = clr_type,
                            },
                            setldetail = setldetail
                        };
                        transaction.Commit();
                        //如果开启了结算接口响应延迟配置 则延迟返回
                        if (FsiDatainfo.stateDrugStroeSettleReturnError == true)
                        {
                            throw new Exception("开启药店结算接口手动报错的配置下，结算接口将返回异常错误，实际结算已成功，此功能仅用于异常对接测试使用，请检查控制台配置。");
                        }
                        //如果开启了结算接口响应延迟配置 则延迟返回
                        if (FsiDatainfo.stateDrugStroeSettleDelay == true)
                        {
                            await Task.Delay(FsiDatainfo.drugStroeSettleDelayTime);
                        }
                        return output;
                    }
                }
            }
        }

        /// <summary>
        /// 2103药店结算撤销
        /// </summary>
        /// <param name="fsiRequest">撤销结算入参</param>
        /// <param name="ControllerName">来源控制器名称</param>
        /// <returns>撤销结算出参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<outputDrugstoreSettleRevoke> DrugstoreSettleRevoke(FsiRequestHeader<InputDrugstoreSettleRevokeRequest> fsiRequest, string ControllerName)
        {
            string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
            string fixmedins_code = fsiRequest.fixmedins_code;
            string setl_id = fsiRequest.Input.data.setl_id;
            string psn_no = fsiRequest.Input.data.psn_no;
            string mdtrtid = fsiRequest.Input.data.mdtrt_id;
            if (string.IsNullOrEmpty(fixmedins_code) || string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(mdtrtid) || string.IsNullOrEmpty(setl_id))
            {
                throw new Exception("参数校验失败：传入的结算id|人员编号||就诊ID为空，请检查入参！");
            }
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            Random rnd = new Random();
            DateTime dateTime = DateTime.Now;
            string query = "select * from fsi_PsnInfo where psn_no=@psn_no";
            var parameters = new List<MySqlParameter>
            {
                new MySqlParameter("@psn_no", psn_no),
                new MySqlParameter("@mdtrt_id",mdtrtid),
                new MySqlParameter("@setl_id",setl_id)
            };
            DataTable dtpsninfo = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameters);
            if (dtpsninfo.Rows.Count != 1)
            {
                throw new Exception($"查询人员信息表失败！根据传入的人员编号【{psn_no}】查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
            }
            query = "select * from fsi_drugstore_order where psn_no=@psn_no and mdtrt_id=@mdtrt_id and setl_id=@setl_id and order_state=1 and order_canceltype=0";
            DataTable dtorderinfo = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameters);
            if (dtorderinfo.Rows.Count !=1)
            {
                throw new Exception($"查询结算记录失败！根据传入的人员编号【{psn_no}】就诊id【{mdtrtid}】结算id【{setl_id}】查询到结算完成但未被冲正的订单信息总数为：{dtorderinfo.Rows.Count}。业务提示：若此订单在2025-03-24之前交易则无法被退款(订单表改造)，若总数非0请联系管理员排查！");
            }
            query = "select * from fsi_drugstore_order_detail where psn_no=@psn_no and mdtrt_id=@mdtrt_id and setl_id=@setl_id";
            DataTable dtorderdetail = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameters);
            if (dtorderdetail.Rows.Count ==0)
            {
                throw new Exception($"查询结算记录失败！根据传入的人员编号【{psn_no}】就诊id【{mdtrtid}】结算id【{setl_id}】查到了结算完成的订单汇总记录但订单明细总数为:0,请联系管理员排查！");
            }
            query = "select * from fsi_drugstore_order_setldetail where psn_no=@psn_no and mdtrt_id=@mdtrt_id and setl_id=@setl_id";
            DataTable dtordersetldetail =await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameters);
            if (dtorderdetail.Rows.Count ==0)
            {
                throw new Exception($"查询结算记录失败！根据传入的人员编号【{psn_no}】就诊id【{mdtrtid}】结算id【{setl_id}】查到了结算完成的订单汇总记录但订单结算基金分项记录总数为:0,请联系管理员排查！");
            }
            long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
            string revokesetl_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}";
            
            string revokeExpcontentJson = null;
            double medIns_wallet_pay= 0;
            if (ControllerName == "FsiApiZheJiangController" && fsiadmvs == "61")
            {
                var psninfo_exp_content = dtpsninfo.Rows[0]["exp_content"].ToString();
                if (!string.IsNullOrEmpty(psninfo_exp_content))
                {
                    JObject obj = JObject.Parse(psninfo_exp_content);
                    if (obj.TryGetValue("medIns_wallet_balance", out JToken balanceToken))
                    {
                        medIns_wallet_pay = Math.Round(0- double.Parse(dtorderinfo.Rows[0]["medfee_sumamt"].ToString()) * FsiDatainfo.medIns_wallet_pay, 2);
                        Setlinfoexpcontent setlinfoexpcontent = new Setlinfoexpcontent
                        {
                            medIns_wallet_balance = balanceToken.Value<double>()-medIns_wallet_pay,
                            medIns_wallet_pay =medIns_wallet_pay
                        };
                        revokeExpcontentJson = JsonConvert.SerializeObject(setlinfoexpcontent);
                    }
                }
            }
            using (var conn = new MySqlConnection(connectionString))
            {
                await conn.OpenAsync();
                using (MySqlTransaction transaction = conn.BeginTransaction())
                {
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.Transaction = transaction;
                        //处理订单汇总记录
                        try
                        {
                            cmd.CommandText = "INSERT INTO fsi_drugstore_order (order_state,stmt_type,order_source,order_canceltype,"+
                                              "opter_type,opter,opter_name,mdtrtarea_admvs,insuplc_admdvs,fixmedins_code,fixmedins_name,sign_no,"+
                                              "msgid,inf_time,infno,mdtrt_cert_type,mdtrt_cert_no,dise_codg,dise_name,insutype,acct_used_flag,psn_no,"+
                                              "med_type,begntime,exp_content,setl_id,mdtrt_id,psn_name,psn_cert_type,certno,setl_time,medfee_sumamt,"+
                                              "fulamt_ownpay_amt,overlmt_selfpay,preselfpay_amt,inscp_scp_amt,act_pay_dedc,hifp_pay,pool_prop_selfpay,cvlserv_pay,"+
                                              "hifes_pay,hifob_pay,hifmi_pay,hifdm_pay,maf_pay,oth_pay,fund_pay_sumamt,psn_part_amt,acct_pay,psn_cash_pay,balc,acct_mulaid_pay,medins_setl_id,"+
                                              "clr_optins,clr_way,clr_type,clcYearAcctPay,crtYearAcctPay,Q0001,medIns_wallet_pay, create_time,update_time) VALUES (3,0,"+
                                              "@order_source,0,@opter_type,@opter,@opter_name,@mdtrtarea_admvs,@insuplc_admdvs,@fixmedins_code,"+
                                              "@fixmedins_name,@sign_no,@msgid,@inf_time,@infno,@mdtrt_cert_type,@mdtrt_cert_no,@dise_codg,@dise_name,@insutype,"+
                                              "@acct_used_flag,@psn_no,@med_type,@begntime,@exp_content,@setl_id,@mdtrt_id,@psn_name,@psn_cert_type,@certno,@setl_time,"+
                                              "@medfee_sumamt,@fulamt_ownpay_amt,@overlmt_selfpay,@preselfpay_amt,@inscp_scp_amt,@act_pay_dedc,@hifp_pay,@pool_prop_selfpay,"+
                                              "@cvlserv_pay,@hifes_pay,@hifob_pay,@hifmi_pay,@hifdm_pay,@maf_pay,@oth_pay,@fund_pay_sumamt,@psn_part_amt,@acct_pay,@psn_cash_pay,@balc,@acct_mulaid_pay,"+
                                              "@medins_setl_id,@clr_optins,@clr_way,@clr_type,@clcYearAcctPay,@crtYearAcctPay,@medIns_wallet_pay,@Q0001,now(),now());"; 
                            cmd.Parameters.AddWithValue("@order_source", ControllerName);
                            cmd.Parameters.AddWithValue("@opter_type", fsiRequest.opter_type);
                            cmd.Parameters.AddWithValue("@opter", fsiRequest.opter);
                            cmd.Parameters.AddWithValue("@opter_name", fsiRequest.opter_name);
                            cmd.Parameters.AddWithValue("@mdtrtarea_admvs", fsiRequest.mdtrtarea_admvs);
                            cmd.Parameters.AddWithValue("@insuplc_admdvs", fsiRequest.insuplc_admdvs);
                            cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                            cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                            cmd.Parameters.AddWithValue("@sign_no", fsiRequest.sign_no);
                            cmd.Parameters.AddWithValue("@msgid", fsiRequest.msgid);
                            cmd.Parameters.AddWithValue("@inf_time", fsiRequest.inf_time);
                            cmd.Parameters.AddWithValue("@infno", fsiRequest.infno);
                            cmd.Parameters.AddWithValue("@mdtrt_cert_type", dtorderinfo.Rows[0]["mdtrt_cert_type"].ToString());
                            cmd.Parameters.AddWithValue("@mdtrt_cert_no", dtorderinfo.Rows[0]["mdtrt_cert_no"].ToString());
                            cmd.Parameters.AddWithValue("@dise_codg", dtorderinfo.Rows[0]["dise_codg"].ToString());
                            cmd.Parameters.AddWithValue("@dise_name", dtorderinfo.Rows[0]["dise_name"].ToString());
                            cmd.Parameters.AddWithValue("@insutype", dtorderinfo.Rows[0]["insutype"].ToString());
                            cmd.Parameters.AddWithValue("@acct_used_flag", dtorderinfo.Rows[0]["acct_used_flag"].ToString());
                            cmd.Parameters.AddWithValue("@psn_no", dtorderinfo.Rows[0]["psn_no"].ToString());
                            cmd.Parameters.AddWithValue("@med_type", dtorderinfo.Rows[0]["med_type"].ToString());
                            cmd.Parameters.AddWithValue("@begntime", dtorderinfo.Rows[0]["begntime"].ToString());
                            cmd.Parameters.AddWithValue("@exp_content",revokeExpcontentJson);
                            cmd.Parameters.AddWithValue("@setl_id", revokesetl_id);
                            cmd.Parameters.AddWithValue("@mdtrt_id", mdtrtid);
                            cmd.Parameters.AddWithValue("@psn_name",dtpsninfo.Rows[0]["psn_name"].ToString());
                            cmd.Parameters.AddWithValue("@psn_cert_type",dtpsninfo.Rows[0]["psn_cert_type"].ToString());
                            cmd.Parameters.AddWithValue("@certno",dtpsninfo.Rows[0]["certno"].ToString());
                            cmd.Parameters.AddWithValue("@setl_time", dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                            cmd.Parameters.AddWithValue("@medfee_sumamt", 0- double.Parse(dtorderinfo.Rows[0]["medfee_sumamt"].ToString()));
                            cmd.Parameters.AddWithValue("@fulamt_ownpay_amt", 0- double.Parse(dtorderinfo.Rows[0]["fulamt_ownpay_amt"].ToString()));
                            cmd.Parameters.AddWithValue("@overlmt_selfpay", 0- double.Parse(dtorderinfo.Rows[0]["overlmt_selfpay"].ToString()));
                            cmd.Parameters.AddWithValue("@preselfpay_amt", 0- double.Parse(dtorderinfo.Rows[0]["preselfpay_amt"].ToString()));
                            cmd.Parameters.AddWithValue("@inscp_scp_amt", 0- double.Parse(dtorderinfo.Rows[0]["inscp_scp_amt"].ToString()));
                            cmd.Parameters.AddWithValue("@act_pay_dedc", 0- double.Parse(dtorderinfo.Rows[0]["act_pay_dedc"].ToString()));
                            cmd.Parameters.AddWithValue("@hifp_pay", 0- double.Parse(dtorderinfo.Rows[0]["hifp_pay"].ToString()));
                            cmd.Parameters.AddWithValue("@pool_prop_selfpay",dtorderinfo.Rows[0]["pool_prop_selfpay"].ToString());
                            cmd.Parameters.AddWithValue("@cvlserv_pay", 0- double.Parse(dtorderinfo.Rows[0]["cvlserv_pay"].ToString()));
                            cmd.Parameters.AddWithValue("@hifes_pay", 0- double.Parse(dtorderinfo.Rows[0]["hifes_pay"].ToString()));
                            cmd.Parameters.AddWithValue("@hifob_pay", 0- double.Parse(dtorderinfo.Rows[0]["hifob_pay"].ToString()));
                            cmd.Parameters.AddWithValue("@hifmi_pay", 0- double.Parse(dtorderinfo.Rows[0]["hifmi_pay"].ToString()));
                            cmd.Parameters.AddWithValue("@hifdm_pay", 0- double.Parse(dtorderinfo.Rows[0]["hifdm_pay"].ToString()));
                            cmd.Parameters.AddWithValue("@maf_pay", 0- double.Parse(dtorderinfo.Rows[0]["maf_pay"].ToString()));
                            cmd.Parameters.AddWithValue("@oth_pay", 0- double.Parse(dtorderinfo.Rows[0]["oth_pay"].ToString()));
                            cmd.Parameters.AddWithValue("@fund_pay_sumamt", 0- double.Parse(dtorderinfo.Rows[0]["fund_pay_sumamt"].ToString()));
                            cmd.Parameters.AddWithValue("@psn_part_amt", 0- double.Parse(dtorderinfo.Rows[0]["psn_part_amt"].ToString()));
                            cmd.Parameters.AddWithValue("@acct_pay",0- double.Parse(dtorderinfo.Rows[0]["acct_pay"].ToString()));
                            cmd.Parameters.AddWithValue("@psn_cash_pay",0- double.Parse(dtorderinfo.Rows[0]["psn_cash_pay"].ToString()));
                            cmd.Parameters.AddWithValue("@balc", double.Parse(dtorderinfo.Rows[0]["balc"].ToString())+ double.Parse(dtorderinfo.Rows[0]["acct_pay"].ToString()));
                            cmd.Parameters.AddWithValue("@acct_mulaid_pay", 0- double.Parse(dtorderinfo.Rows[0]["acct_mulaid_pay"].ToString()));
                            cmd.Parameters.AddWithValue("@medins_setl_id", fsiRequest.msgid);
                            cmd.Parameters.AddWithValue("@clr_optins",$"{fsiRequest.mdtrtarea_admvs.Substring(0, 4)}99");
                            cmd.Parameters.AddWithValue("@clr_way", dtorderinfo.Rows[0]["clr_way"].ToString());
                            cmd.Parameters.AddWithValue("@clr_type", dtorderinfo.Rows[0]["clr_type"].ToString());
                            cmd.Parameters.AddWithValue("@clcYearAcctPay", 0- double.Parse(dtorderinfo.Rows[0]["clcYearAcctPay"].ToString()));
                            cmd.Parameters.AddWithValue("@crtYearAcctPay", 0- double.Parse(dtorderinfo.Rows[0]["crtYearAcctPay"].ToString()));
                            cmd.Parameters.AddWithValue("@Q0001", 0- double.Parse(dtorderinfo.Rows[0]["Q0001"].ToString()));
                            cmd.Parameters.AddWithValue("@medIns_wallet_pay", 0 - double.Parse(dtorderinfo.Rows[0]["Q0001"].ToString()));
                            await cmd.ExecuteNonQueryAsync();
                            cmd.Parameters.Clear();
                        }
                        catch  (Exception ex)
                        {
                            transaction.Rollback();
                            throw new Exception($"退款处理失败：插入订单汇总记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                        }
                        
                        
                        
                        
                        //处理订单明细记录
                        foreach (DataRow row in dtorderdetail.Rows)
                        {
                            try
                            {
                                 cmd.CommandText = "INSERT INTO fsi_drugstore_order_detail (msgid,setl_id,mdtrt_id,psn_no,feedetl_sn,rxno,rx_circ_flag,fee_ocur_time," +
                                              "med_list_codg,medins_list_codg,det_item_fee_sumamt,cnt,pric,sin_dos_dscr,used_frqu_dscr,prd_days,medc_way_dscr," +
                                              "bilg_dr_codg,bilg_dr_name,tcmdrug_used_way,exp_content,pric_uplmt_amt,selfpay_prop,fulamt_ownpay_amt,overlmt_amt," +
                                              "preselfpay_amt,inscp_scp_amt,chrgitm_lv,med_chrgitm_type,bas_medn_flag,hi_nego_drug_flag,chld_medc_flag,list_sp_item_flag," +
                                              "drt_reim_flag,memo,create_time,update_time) VALUES (@msgid,@setl_id,@mdtrt_id,@psn_no,@feedetl_sn,@rxno,@rx_circ_flag,@fee_ocur_time," +
                                              "@med_list_codg,@medins_list_codg,@det_item_fee_sumamt,@cnt,@pric,@sin_dos_dscr,@used_frqu_dscr,@prd_days,@medc_way_dscr,@bilg_dr_codg," +
                                              "@bilg_dr_name,@tcmdrug_used_way,@exp_content,@pric_uplmt_amt,@selfpay_prop,@fulamt_ownpay_amt,@overlmt_amt,@preselfpay_amt,@inscp_scp_amt," +
                                              "@chrgitm_lv,@med_chrgitm_type,@bas_medn_flag,@hi_nego_drug_flag,@chld_medc_flag,@list_sp_item_flag,@drt_reim_flag,@memo,now(),now())";
                                cmd.Parameters.AddWithValue("@msgid", fsiRequest.msgid);
                                cmd.Parameters.AddWithValue("@setl_id", revokesetl_id);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrtid);
                                cmd.Parameters.AddWithValue("@psn_no", psn_no);
                                cmd.Parameters.AddWithValue("@feedetl_sn", row["feedetl_sn"].ToString());
                                cmd.Parameters.AddWithValue("@rxno", row["rxno"].ToString());
                                cmd.Parameters.AddWithValue("@rx_circ_flag", row["rx_circ_flag"].ToString());
                                cmd.Parameters.AddWithValue("@fee_ocur_time", row["fee_ocur_time"].ToString());
                                cmd.Parameters.AddWithValue("@med_list_codg", row["med_list_codg"].ToString());
                                cmd.Parameters.AddWithValue("@medins_list_codg", row["medins_list_codg"].ToString());
                                cmd.Parameters.AddWithValue("@det_item_fee_sumamt", 0- double.Parse(row["det_item_fee_sumamt"].ToString()));
                                cmd.Parameters.AddWithValue("@cnt", 0- double.Parse(row["cnt"].ToString()));
                                cmd.Parameters.AddWithValue("@pric", 0- double.Parse(row["pric"].ToString()));
                                cmd.Parameters.AddWithValue("@sin_dos_dscr", row["sin_dos_dscr"].ToString());
                                cmd.Parameters.AddWithValue("@used_frqu_dscr", row["used_frqu_dscr"].ToString());
                                cmd.Parameters.AddWithValue("@prd_days", row["prd_days"].ToString());
                                cmd.Parameters.AddWithValue("@medc_way_dscr", row["medc_way_dscr"].ToString());
                                cmd.Parameters.AddWithValue("@bilg_dr_codg", row["bilg_dr_codg"].ToString());
                                cmd.Parameters.AddWithValue("@bilg_dr_name", row["bilg_dr_name"].ToString());
                                cmd.Parameters.AddWithValue("@tcmdrug_used_way", row["tcmdrug_used_way"].ToString());
                                cmd.Parameters.AddWithValue("@exp_content", row["exp_content"].ToString());
                                cmd.Parameters.AddWithValue("@pric_uplmt_amt",  0- double.Parse(row["pric_uplmt_amt"].ToString()));
                                cmd.Parameters.AddWithValue("@selfpay_prop", 0- double.Parse(row["selfpay_prop"].ToString()));
                                cmd.Parameters.AddWithValue("@fulamt_ownpay_amt", 0- double.Parse(row["fulamt_ownpay_amt"].ToString()));
                                cmd.Parameters.AddWithValue("@overlmt_amt", 0- double.Parse(row["overlmt_amt"].ToString()));
                                cmd.Parameters.AddWithValue("@preselfpay_amt", 0- double.Parse(row["preselfpay_amt"].ToString()));
                                cmd.Parameters.AddWithValue("@inscp_scp_amt", 0- double.Parse(row["det_item_fee_sumamt"].ToString()));
                                cmd.Parameters.AddWithValue("@chrgitm_lv", row["chrgitm_lv"].ToString());
                                cmd.Parameters.AddWithValue("@med_chrgitm_type", row["med_chrgitm_type"].ToString());
                                cmd.Parameters.AddWithValue("@bas_medn_flag", row["bas_medn_flag"].ToString());
                                cmd.Parameters.AddWithValue("@hi_nego_drug_flag", row["hi_nego_drug_flag"].ToString());
                                cmd.Parameters.AddWithValue("@chld_medc_flag", row["chld_medc_flag"].ToString());
                                cmd.Parameters.AddWithValue("@list_sp_item_flag", row["list_sp_item_flag"].ToString());
                                cmd.Parameters.AddWithValue("@drt_reim_flag", row["drt_reim_flag"].ToString());
                                cmd.Parameters.AddWithValue("@memo",row["memo"].ToString());
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"退款处理失败：插入订单明细【{row["med_list_codg"].ToString()}】记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                        }
                        //处理结算基金明细
                        List<Setldetail> dataList = new List<Setldetail>();
                        foreach (DataRow row in dtordersetldetail.Rows)
                        {
                            try
                            {
                                cmd.CommandText =
                                    "INSERT INTO fsi_drugstore_order_setldetail (msgid,setl_id,mdtrt_id,psn_no,fund_pay_type,inscp_scp_amt,crt_payb_lmt_amt," +
                                    "fund_payamt,fund_pay_type_name,setl_proc_info,create_time,update_time) VALUES (@msgid,@setl_id,@mdtrt_id,@psn_no,@fund_pay_type," +
                                    "@inscp_scp_amt,@crt_payb_lmt_amt,@fund_payamt,@fund_pay_type_name,@setl_proc_info,now(),now())";
                                cmd.Parameters.AddWithValue("@msgid", fsiRequest.msgid);
                                cmd.Parameters.AddWithValue("@setl_id", revokesetl_id);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrtid);
                                cmd.Parameters.AddWithValue("@psn_no", psn_no);
                                cmd.Parameters.AddWithValue("@fund_pay_type",row["fund_pay_type"].ToString());
                                cmd.Parameters.AddWithValue("@inscp_scp_amt", row["inscp_scp_amt"].ToString());
                                cmd.Parameters.AddWithValue("@crt_payb_lmt_amt", row["crt_payb_lmt_amt"].ToString()) ;
                                cmd.Parameters.AddWithValue("@fund_payamt", 0- double.Parse(row["fund_payamt"].ToString()));
                                cmd.Parameters.AddWithValue("@fund_pay_type_name", row["fund_pay_type_name"].ToString());
                                cmd.Parameters.AddWithValue("@setl_proc_info", row["setl_proc_info"].ToString());
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"退款处理失败：插入结算基金记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            //序列化基金支付风项
                            setl_proc_info setlprocinfo = new setl_proc_info
                            {
                                hifpPayInscp = double.Parse(row["fund_payamt"].ToString()),
                                polItemCode = "LA01",
                                poolPropSelfpay = 0,
                                hifpPay = double.Parse(row["fund_payamt"].ToString())
                            };
                            string expcontentJson = JsonConvert.SerializeObject(setlprocinfo);
                            if (row["fund_pay_type"].ToString() == "310200")
                            {
                                Setldetail setldetail = new Setldetail
                                {
                                    fund_pay_type = row["fund_pay_type"].ToString(),
                                    fund_payamt = 0 - double.Parse(row["fund_payamt"].ToString()),
                                    setl_proc_info = expcontentJson,
                                    crt_payb_lmt_amt = 0 - double.Parse(row["crt_payb_lmt_amt"].ToString()),
                                    inscp_scp_amt = 0 - double.Parse(row["inscp_scp_amt"].ToString()),
                                    fund_pay_type_name = row["fund_pay_type_name"].ToString()
                                };
                                dataList.Add(setldetail);
                            }
                            else
                            {
                                Setldetail setldetail = new Setldetail
                                {
                                    fund_pay_type = row["fund_pay_type"].ToString(),
                                    fund_payamt = 0 - double.Parse(row["fund_payamt"].ToString()),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0 - double.Parse(row["crt_payb_lmt_amt"].ToString()),
                                    inscp_scp_amt = 0 - double.Parse(row["inscp_scp_amt"].ToString()),
                                    fund_pay_type_name = row["fund_pay_type_name"].ToString()
                                };
                                dataList.Add(setldetail);
                            }
                        }
                        //插入年度费用累计
                        try
                        {
                            await _drugStoreCommonService.InsertQueryfixmedinspracpsnsum(
                                psn_no, "S1100", dateTime.ToString("yyyy"),
                                0-decimal.Parse(dtorderinfo.Rows[0]["medfee_sumamt"].ToString()),
                                dateTime.ToString("yyyyMM"), dtpsninfo.Rows[0]["insutype"].ToString(), transaction);
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            throw new Exception($"退款数据处理失败：插入费用累计记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                        }
                        var output = new outputDrugstoreSettleRevoke
                        {
                            setlinfo = new SetlinfoRevoke
                            {
                                setl_time = dateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                cvlserv_pay = 0- double.Parse(dtorderinfo.Rows[0]["cvlserv_pay"].ToString()),
                                hifdm_pay = 0- double.Parse(dtorderinfo.Rows[0]["hifdm_pay"].ToString()),
                                psn_pay = 0- double.Parse(dtorderinfo.Rows[0]["psn_cash_pay"].ToString()),
                                hifmi_pay = 0- double.Parse(dtorderinfo.Rows[0]["hifmi_pay"].ToString()),
                                act_pay_dedc = 0- double.Parse(dtorderinfo.Rows[0]["act_pay_dedc"].ToString()),
                                balc = double.Parse(dtorderinfo.Rows[0]["balc"].ToString())+ double.Parse(dtorderinfo.Rows[0]["acct_pay"].ToString()),
                                medins_setl_id = fsiRequest.msgid,
                                exp_content = revokeExpcontentJson,
                                acct_mulaid_pay = 0- double.Parse(dtorderinfo.Rows[0]["acct_mulaid_pay"].ToString()),
                                hifob_pay = 0- double.Parse(dtorderinfo.Rows[0]["hifob_pay"].ToString()),
                                oth_pay = 0- double.Parse(dtorderinfo.Rows[0]["oth_pay"].ToString()),
                                medfee_sumamt = 0- double.Parse(dtorderinfo.Rows[0]["medfee_sumamt"].ToString()),
                                hifes_pay = 0 - double.Parse(dtorderinfo.Rows[0]["hifes_pay"].ToString()),
                                mdtrt_id = mdtrtid,
                                acct_pay = 0 - double.Parse(dtorderinfo.Rows[0]["acct_pay"].ToString()),
                                fund_pay_sumamt = 0 - double.Parse(dtorderinfo.Rows[0]["fund_pay_sumamt"].ToString()),
                                fulamt_ownpay_amt = 0 - double.Parse(dtorderinfo.Rows[0]["fulamt_ownpay_amt"].ToString()),
                                setl_id = revokesetl_id,
                                inscp_scp_amt = 0- double.Parse(dtorderinfo.Rows[0]["inscp_scp_amt"].ToString()),
                                maf_pay = 0 - double.Parse(dtorderinfo.Rows[0]["maf_pay"].ToString()),
                                clr_optins = $"{fsiRequest.mdtrtarea_admvs.Substring(0, 4)}99",
                                pool_prop_selfpay = double.Parse(dtorderinfo.Rows[0]["pool_prop_selfpay"].ToString()),
                                hifp_pay = 0- double.Parse(dtorderinfo.Rows[0]["hifp_pay"].ToString()),
                                overlmt_selfpay = 0- double.Parse(dtorderinfo.Rows[0]["overlmt_selfpay"].ToString()),
                                preselfpay_amt = 0- double.Parse(dtorderinfo.Rows[0]["preselfpay_amt"].ToString())
                            },
                            setldetail = dataList
                        };
                        transaction.Commit(); 
                        //如果开启了结算接口响应延迟配置 则延迟返回
                        if (FsiDatainfo.stateDrugStroeSettleDelay == true)
                        {
                            await Task.Delay(FsiDatainfo.drugStroeSettleDelayTime);
                        }
                        return output;
                    }
                }
            }
        }
        
        /// <summary>
        /// 2101/2101A药店预结算-测试服务(只用来临时调整测试服务)
        /// </summary>
        /// <param name="fsiRequest">预结算入参</param>
        /// <param name="ControllerName">来源控制器名称</param>
        /// <returns>预结算出参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<outputDrugstoreSettleAccountsPreA> DrugstoreSettleAccountsPre_test(FsiRequestHeader<InputDrugstoreSettleAccountsPreA> fsiRequest, string ControllerName)
        {
            List<DrugdetailDrugstoreSettleAccountsPreA> list = new List<DrugdetailDrugstoreSettleAccountsPreA>();
            list = fsiRequest.Input.drugdetail;
            string psn_no = fsiRequest.Input.druginfo.psn_no;
            string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
            if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(fsiRequest.fixmedins_code) || list.Count == 0)
            {
                throw new Exception("参数校验失败：传入的机构代码|人员编号|待结算的商品数组为空，请检查入参！" );
            }
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            Random rnd = new Random();
            DateTime dateTime = DateTime.Now;
            string query = "select * from fsi_PsnInfo where psn_no=@psn_no";
            var parameters = new List<MySqlParameter>
            {
                new MySqlParameter("@psn_no", psn_no),
            };
            DataTable dtpsninfo = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameters);
            if (dtpsninfo.Rows.Count != 1)
            {
                throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
            }
            //清算类型 如果传入的是定点购药41 则清算类型为41药店，否则统一为11 门诊（不区分住院外配归到住院的部分）
            string clr_type = fsiRequest.Input.druginfo.med_type == "41" ? "41" : "11";
            // 生成就诊id 伪随机数
            string mdtrt_id = rnd.Next(10000000, 90000000).ToString();
            using (var conn = new MySqlConnection(connectionString))
            {
                await conn.OpenAsync();
                using (MySqlTransaction transaction = conn.BeginTransaction())
                {
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {                        
                        cmd.Transaction = transaction; 
                        //处理订单汇总记录
                        try
                        {
                            cmd.CommandText = "INSERT INTO fsi_drugstore_order (order_state,stmt_type,order_source,order_canceltype,"+
                                              "opter_type,opter,opter_name,mdtrtarea_admvs,insuplc_admdvs,fixmedins_code,fixmedins_name,sign_no,"+
                                              "msgid,inf_time,infno,mdtrt_cert_type,mdtrt_cert_no,dise_codg,dise_name,insutype,acct_used_flag,psn_no,"+
                                              "med_type,begntime,exp_content,minpacunt_drug_trac_cnt,mcs_trac_cnt,setl_id,mdtrt_id,psn_name,psn_cert_type,certno,setl_time,medfee_sumamt,"+
                                              "fulamt_ownpay_amt,overlmt_selfpay,preselfpay_amt,inscp_scp_amt,act_pay_dedc,hifp_pay,pool_prop_selfpay,cvlserv_pay,"+
                                              "hifes_pay,hifob_pay,hifmi_pay,hifdm_pay,maf_pay,oth_pay,fund_pay_sumamt,psn_part_amt,acct_pay,psn_cash_pay,balc,acct_mulaid_pay,medins_setl_id,"+
                                              "clr_optins,clr_way,clr_type,clcYearAcctPay,crtYearAcctPay,Q0001,create_time,update_time) VALUES (0,0,"+
                                              "@order_source,0,@opter_type,@opter,@opter_name,@mdtrtarea_admvs,@insuplc_admdvs,@fixmedins_code,"+
                                              "@fixmedins_name,@sign_no,@msgid,@inf_time,@infno,@mdtrt_cert_type,@mdtrt_cert_no,@dise_codg,@dise_name,@insutype,"+
                                              "@acct_used_flag,@psn_no,@med_type,@begntime,@exp_content,@minpacunt_drug_trac_cnt,@mcs_trac_cnt,@setl_id,@mdtrt_id,@psn_name,@psn_cert_type,@certno,@setl_time,"+
                                              "@medfee_sumamt,@fulamt_ownpay_amt,@overlmt_selfpay,@preselfpay_amt,@inscp_scp_amt,@act_pay_dedc,@hifp_pay,@pool_prop_selfpay,"+
                                              "@cvlserv_pay,@hifes_pay,@hifob_pay,@hifmi_pay,@hifdm_pay,@maf_pay,@oth_pay,@fund_pay_sumamt,@psn_part_amt,@acct_pay,@psn_cash_pay,@balc,@acct_mulaid_pay,"+
                                              "@medins_setl_id,@clr_optins,@clr_way,@clr_type,@clcYearAcctPay,@crtYearAcctPay,@Q0001,now(),now());"; 
                            cmd.Parameters.AddWithValue("@order_source", ControllerName);
                            cmd.Parameters.AddWithValue("@opter_type", fsiRequest.opter_type);
                            cmd.Parameters.AddWithValue("@opter", fsiRequest.opter);
                            cmd.Parameters.AddWithValue("@opter_name", fsiRequest.opter_name);
                            cmd.Parameters.AddWithValue("@mdtrtarea_admvs", fsiRequest.mdtrtarea_admvs);
                            cmd.Parameters.AddWithValue("@insuplc_admdvs", fsiRequest.insuplc_admdvs);
                            cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                            cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                            cmd.Parameters.AddWithValue("@sign_no", fsiRequest.sign_no);
                            cmd.Parameters.AddWithValue("@msgid", fsiRequest.msgid);
                            cmd.Parameters.AddWithValue("@inf_time", fsiRequest.inf_time);
                            cmd.Parameters.AddWithValue("@infno", fsiRequest.infno);
                            cmd.Parameters.AddWithValue("@mdtrt_cert_type", fsiRequest.Input.druginfo.mdtrt_cert_type);
                            cmd.Parameters.AddWithValue("@mdtrt_cert_no", fsiRequest.Input.druginfo.mdtrt_cert_no);
                            cmd.Parameters.AddWithValue("@dise_codg", fsiRequest.Input.druginfo.dise_codg);
                            cmd.Parameters.AddWithValue("@dise_name", fsiRequest.Input.druginfo.dise_name);
                            cmd.Parameters.AddWithValue("@insutype", fsiRequest.Input.druginfo.insutype);
                            cmd.Parameters.AddWithValue("@acct_used_flag", fsiRequest.Input.druginfo.acct_used_flag);
                            cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.druginfo.psn_no);
                            cmd.Parameters.AddWithValue("@med_type", fsiRequest.Input.druginfo.med_type);
                            cmd.Parameters.AddWithValue("@begntime", fsiRequest.Input.druginfo.begntime);
                            cmd.Parameters.AddWithValue("@exp_content","拓展字段保留");
                            cmd.Parameters.AddWithValue("@minpacunt_drug_trac_cnt", fsiRequest.Input.druginfo.minpacunt_drug_trac_cnt);
                            cmd.Parameters.AddWithValue("@mcs_trac_cnt", fsiRequest.Input.druginfo.mcs_trac_cnt);
                            cmd.Parameters.AddWithValue("@setl_id", "");
                            cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                            cmd.Parameters.AddWithValue("@psn_name",dtpsninfo.Rows[0]["psn_name"].ToString());
                            cmd.Parameters.AddWithValue("@psn_cert_type",dtpsninfo.Rows[0]["psn_cert_type"].ToString());
                            cmd.Parameters.AddWithValue("@certno",dtpsninfo.Rows[0]["certno"].ToString());
                            cmd.Parameters.AddWithValue("@setl_time", dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                            cmd.Parameters.AddWithValue("@medfee_sumamt", fsiRequest.Input.druginfo.medfee_sumamt);
                            cmd.Parameters.AddWithValue("@fulamt_ownpay_amt", FsiDatainfo.fulamt_ownpay_amt);
                            cmd.Parameters.AddWithValue("@overlmt_selfpay", FsiDatainfo.overlmt_selfpay);
                            cmd.Parameters.AddWithValue("@preselfpay_amt", FsiDatainfo.preselfpay_amt);
                            cmd.Parameters.AddWithValue("@inscp_scp_amt", FsiDatainfo.inscp_scp_amt);
                            cmd.Parameters.AddWithValue("@act_pay_dedc", FsiDatainfo.act_pay_dedc);
                            cmd.Parameters.AddWithValue("@hifp_pay", fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt);
                            cmd.Parameters.AddWithValue("@pool_prop_selfpay",FsiDatainfo.fund_pay_sumamt);
                            cmd.Parameters.AddWithValue("@cvlserv_pay", FsiDatainfo.cvlserv_pay);
                            cmd.Parameters.AddWithValue("@hifes_pay", FsiDatainfo.hifes_pay);
                            cmd.Parameters.AddWithValue("@hifob_pay", FsiDatainfo.hifob_pay);
                            cmd.Parameters.AddWithValue("@hifmi_pay", FsiDatainfo.hifmi_pay);
                            cmd.Parameters.AddWithValue("@hifdm_pay", FsiDatainfo.hifdm_pay);
                            cmd.Parameters.AddWithValue("@maf_pay", FsiDatainfo.maf_pay);
                            cmd.Parameters.AddWithValue("@oth_pay", FsiDatainfo.oth_pay);
                            cmd.Parameters.AddWithValue("@fund_pay_sumamt", Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2));
                            cmd.Parameters.AddWithValue("@psn_part_amt", fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt);
                            cmd.Parameters.AddWithValue("@acct_pay",Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2));
                            cmd.Parameters.AddWithValue("@psn_cash_pay",Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.psn_cash_pay, 2));
                            cmd.Parameters.AddWithValue("@balc", Math.Round(Convert.ToDouble(dtpsninfo.Rows[0]["balc"]) - Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2), 2));
                            cmd.Parameters.AddWithValue("@acct_mulaid_pay", Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_mulaid_pay, 2));
                            cmd.Parameters.AddWithValue("@medins_setl_id", fsiRequest.msgid);
                            cmd.Parameters.AddWithValue("@clr_optins",$"{fsiRequest.mdtrtarea_admvs.Substring(0, 4)}99");
                            cmd.Parameters.AddWithValue("@clr_way", 1);
                            cmd.Parameters.AddWithValue("@clr_type", clr_type);
                            cmd.Parameters.AddWithValue("@clcYearAcctPay", null);
                            cmd.Parameters.AddWithValue("@crtYearAcctPay", null);
                            cmd.Parameters.AddWithValue("@Q0001", null);
                            await cmd.ExecuteNonQueryAsync();
                            cmd.Parameters.Clear();
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            throw new Exception($"预结算处理失败：插入订单汇总记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                        }
                        //处理订单明细记录
                        List<Detlcutinfo> dataList = new List<Detlcutinfo>();
                        foreach (var item in list)
                        {
                            //如果医疗类型不为41定点购药且处方号不为空，则校验处方号中是否存在该商品
                            //(fsiRequest.Input.druginfo.med_type != "41" || (ControllerName == "FsiApiZheJiangController" && fsiadmvs == "61")) && 
                            if (!string.IsNullOrEmpty(item.rxno))
                            {
                                bool isVerify = await _drugStoreCommonService.VerifyPrescriptionDrugs(item.rxno, fsiRequest.Input.druginfo.med_type, item.med_list_codg);
                                if (!isVerify)
                                {
                                    transaction.Rollback();
                                    throw new Exception($"处方药品明细校验失败：【{item.med_list_codg}】商品不存于处方【{item.rxno}】中。请注意只有在普通门诊处方下可以允许同一个药品替换同剂型同通用名不同厂家不同国家编码，其他医疗类别的处方强制要求处方上的国家编码与结算时入参的药品编码一致！【西药前18位编码一致，中成药前15位编码一致】，不符合业务要求！请检查!");
                                }
                            }

                            try
                            {
                                 cmd.CommandText = "INSERT INTO fsi_drugstore_order_detail (msgid,setl_id,mdtrt_id,psn_no,feedetl_sn,rxno,rx_circ_flag,fee_ocur_time," +
                                              "med_list_codg,medins_list_codg,det_item_fee_sumamt,cnt,pric,sin_dos_dscr,used_frqu_dscr,prd_days,medc_way_dscr," +
                                              "bilg_dr_codg,bilg_dr_name,tcmdrug_used_way,exp_content,pric_uplmt_amt,selfpay_prop,fulamt_ownpay_amt,overlmt_amt," +
                                              "preselfpay_amt,inscp_scp_amt,chrgitm_lv,med_chrgitm_type,bas_medn_flag,hi_nego_drug_flag,chld_medc_flag,list_sp_item_flag," +
                                              "drt_reim_flag,memo,create_time,update_time) VALUES (@msgid,@setl_id,@mdtrt_id,@psn_no,@feedetl_sn,@rxno,@rx_circ_flag,@fee_ocur_time," +
                                              "@med_list_codg,@medins_list_codg,@det_item_fee_sumamt,@cnt,@pric,@sin_dos_dscr,@used_frqu_dscr,@prd_days,@medc_way_dscr,@bilg_dr_codg," +
                                              "@bilg_dr_name,@tcmdrug_used_way,@exp_content,@pric_uplmt_amt,@selfpay_prop,@fulamt_ownpay_amt,@overlmt_amt,@preselfpay_amt,@inscp_scp_amt," +
                                              "@chrgitm_lv,@med_chrgitm_type,@bas_medn_flag,@hi_nego_drug_flag,@chld_medc_flag,@list_sp_item_flag,@drt_reim_flag,@memo,now(),now())";
                                cmd.Parameters.AddWithValue("@msgid", fsiRequest.msgid);
                                cmd.Parameters.AddWithValue("@setl_id", null);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@psn_no", psn_no);
                                cmd.Parameters.AddWithValue("@feedetl_sn", item.feedetl_sn);
                                cmd.Parameters.AddWithValue("@rxno", item.rxno);
                                cmd.Parameters.AddWithValue("@rx_circ_flag", item.rx_circ_flag);
                                cmd.Parameters.AddWithValue("@fee_ocur_time", item.fee_ocur_time);
                                cmd.Parameters.AddWithValue("@med_list_codg", item.med_list_codg);
                                cmd.Parameters.AddWithValue("@medins_list_codg", item.medins_list_codg);
                                cmd.Parameters.AddWithValue("@det_item_fee_sumamt", item.det_item_fee_sumamt);
                                cmd.Parameters.AddWithValue("@cnt", item.cnt);
                                cmd.Parameters.AddWithValue("@pric", item.pric);
                                cmd.Parameters.AddWithValue("@sin_dos_dscr", item.sin_dos_dscr);
                                cmd.Parameters.AddWithValue("@used_frqu_dscr", item.used_frqu_dscr);
                                cmd.Parameters.AddWithValue("@prd_days", item.prd_days);
                                cmd.Parameters.AddWithValue("@medc_way_dscr", item.medc_way_dscr);
                                cmd.Parameters.AddWithValue("@bilg_dr_codg", item.bilg_dr_codg);
                                cmd.Parameters.AddWithValue("@bilg_dr_name", item.bilg_dr_name);
                                cmd.Parameters.AddWithValue("@tcmdrug_used_way", item.tcmdrug_used_way);
                                cmd.Parameters.AddWithValue("@exp_content", null);
                                cmd.Parameters.AddWithValue("@pric_uplmt_amt", item.det_item_fee_sumamt);
                                cmd.Parameters.AddWithValue("@selfpay_prop", 0);
                                cmd.Parameters.AddWithValue("@fulamt_ownpay_amt", 0);
                                cmd.Parameters.AddWithValue("@overlmt_amt", 0);
                                cmd.Parameters.AddWithValue("@preselfpay_amt", 0);
                                cmd.Parameters.AddWithValue("@inscp_scp_amt", item.det_item_fee_sumamt);
                                cmd.Parameters.AddWithValue("@chrgitm_lv", "03");
                                cmd.Parameters.AddWithValue("@med_chrgitm_type", "09");
                                cmd.Parameters.AddWithValue("@bas_medn_flag", "0");
                                cmd.Parameters.AddWithValue("@hi_nego_drug_flag", "0");
                                cmd.Parameters.AddWithValue("@chld_medc_flag", "0");
                                cmd.Parameters.AddWithValue("@list_sp_item_flag", "0");
                                cmd.Parameters.AddWithValue("@drt_reim_flag", "0");
                                cmd.Parameters.AddWithValue("@memo", null);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                                Detlcutinfo detlcutinfo = new Detlcutinfo
                                {
                                    bas_medn_flag = null,
                                    med_chrgitm_type = "09",
                                    det_item_fee_sumamt = item.det_item_fee_sumamt,
                                    hi_nego_drug_flag = "0",
                                    fulamt_ownpay_amt = 0,
                                    cnt = item.cnt,
                                    pric = item.pric,
                                    feedetl_sn = item.feedetl_sn,
                                    inscp_scp_amt = item.det_item_fee_sumamt,
                                    drt_reim_flag = "0",
                                    overlmt_amt = 0,
                                    pric_uplmt_amt = item.det_item_fee_sumamt,
                                    selfpay_prop = 0,
                                    preselfpay_amt = 0,
                                    chrgitm_lv = null
                                };
                                dataList.Add(detlcutinfo);
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"预结算处理失败：插入订单明细【{item.med_list_codg}】记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                        }
                        //处理结算基金记录
                        List<Setldetail> setldetail = new List<Setldetail>();
                        try
                        {
                            cmd.CommandText =
                                "INSERT INTO fsi_drugstore_order_setldetail (msgid,setl_id,mdtrt_id,psn_no,fund_pay_type,inscp_scp_amt,crt_payb_lmt_amt," +
                                "fund_payamt,fund_pay_type_name,setl_proc_info,create_time,update_time) VALUES (@msgid,@setl_id,@mdtrt_id,@psn_no,@fund_pay_type," +
                                "@inscp_scp_amt,@crt_payb_lmt_amt,@fund_payamt,@fund_pay_type_name,@setl_proc_info,now(),now())";
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay != 0)
                            {
                                cmd.Parameters.AddWithValue("@msgid", fsiRequest.msgid);
                                cmd.Parameters.AddWithValue("@setl_id", null);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@psn_no", psn_no);
                                cmd.Parameters.AddWithValue("@fund_pay_type", "310200");
                                cmd.Parameters.AddWithValue("@inscp_scp_amt", 0);
                                cmd.Parameters.AddWithValue("@crt_payb_lmt_amt", 0);
                                cmd.Parameters.AddWithValue("@fund_payamt", Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2));
                                cmd.Parameters.AddWithValue("@fund_pay_type_name", "城镇职工基本医疗保险个人账户基金");
                                cmd.Parameters.AddWithValue("@setl_proc_info", null);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                                
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310200",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险个人账户基金"
                                };
                                setldetail.Add(detail);
                            }
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt != 0)
                            {
                                cmd.Parameters.AddWithValue("@msgid", fsiRequest.msgid);
                                cmd.Parameters.AddWithValue("@setl_id", null);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@psn_no", psn_no);
                                cmd.Parameters.AddWithValue("@fund_pay_type", "310100");
                                cmd.Parameters.AddWithValue("@inscp_scp_amt", 0);
                                cmd.Parameters.AddWithValue("@crt_payb_lmt_amt", 0);
                                cmd.Parameters.AddWithValue("@fund_payamt", Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2));
                                cmd.Parameters.AddWithValue("@fund_pay_type_name", "城镇职工基本医疗保险统筹基金");
                                cmd.Parameters.AddWithValue("@setl_proc_info", null);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310100",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险统筹基金"
                                };
                                setldetail.Add(detail);
                            }
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            throw new Exception($"预结算处理失败：插入结算基金记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                        }
                        transaction.Commit();
                        var output = new outputDrugstoreSettleAccountsPreA
                        {
                            detlcutinfo = dataList,
                            setlinfo = new Setlinfo
                            {
                                setl_time =null,
                                cvlserv_pay = FsiDatainfo.cvlserv_pay,//公务员医疗补助资金
                                hifdm_pay = FsiDatainfo.hifdm_pay,//伤残人员医疗保障基金支出
                                cvlserv_flag = dtpsninfo.Rows[0]["cvlserv_flag"].ToString(),//公务员标志
                                med_type = fsiRequest.Input.druginfo.med_type,
                                brdy = dtpsninfo.Rows[0]["brdy"].ToString(),
                                naty = dtpsninfo.Rows[0]["naty"].ToString(),//民族
                                psn_cash_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.psn_cash_pay, 2),//现金支付
                                certno =  dtpsninfo.Rows[0]["certno"].ToString(),//身份证号码
                                hifmi_pay = FsiDatainfo.hifmi_pay,//居民大病保险资金支出
                                psn_no = fsiRequest.Input.druginfo.psn_no,
                                act_pay_dedc = FsiDatainfo.act_pay_dedc,//实际支付起付线
                                mdtrt_cert_type = fsiRequest.Input.druginfo.mdtrt_cert_type,
                                balc = Math.Round(Convert.ToDouble(dtpsninfo.Rows[0]["balc"]) - Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2), 2),
                                medins_setl_id = fsiRequest.msgid,
                                psn_cert_type = dtpsninfo.Rows[0]["psn_cert_type"].ToString(),
                                acct_mulaid_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_mulaid_pay, 2),//个人账户共济支付金额
                                clr_way = "1",
                                hifob_pay = FsiDatainfo.hifob_pay,//职工大额医疗费用补助基金支出
                                oth_pay = FsiDatainfo.oth_pay,//其他支出
                                medfee_sumamt = fsiRequest.Input.druginfo.medfee_sumamt,
                                hifes_pay = FsiDatainfo.hifes_pay,//企业补充医疗保险基金支出
                                gend = dtpsninfo.Rows[0]["gend"].ToString(),
                                mdtrt_id = mdtrt_id,
                                acct_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),//个人账户支出
                                fund_pay_sumamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),//基金支付
                                fulamt_ownpay_amt = FsiDatainfo.fulamt_ownpay_amt,//全自费金额
                                hosp_part_amt = FsiDatainfo.hosp_part_amt,//医院负担金额
                                inscp_scp_amt = FsiDatainfo.inscp_scp_amt,//符合政策范围金额
                                insutype = fsiRequest.Input.druginfo.insutype,
                                maf_pay = FsiDatainfo.maf_pay, //医疗救助基金支出
                                psn_name = dtpsninfo.Rows[0]["psn_name"].ToString(),
                                psn_part_amt = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //个人负担总额
                                clr_optins = $"{fsiRequest.mdtrtarea_admvs.Substring(0, 4)}99",
                                pool_prop_selfpay = FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支付比例
                                psn_type =  dtpsninfo.Rows[0]["psn_type"].ToString(),
                                hifp_pay = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支出
                                overlmt_selfpay = FsiDatainfo.overlmt_selfpay, //超限价金额
                                preselfpay_amt = FsiDatainfo.preselfpay_amt, //先行自付金额
                                age = PublicMethod.CalculateAge(dtpsninfo.Rows[0]["brdy"].ToString(), dateTime),
                                clr_type = clr_type,
                            },
                            setldetail = setldetail
                        };
                        return output;
                    }
                }
            }
        }
        
    
    
    }
}
